Osman Rafi
Osman Rafi

Reputation: 1046

Render v-html without extra wrapping tag?

In vue 2 v-html require to render an extra wrapping tag. But I'm trying something like following.

<select v-model="coutnry">
 // here the options to be rendered.
</select>


<script>
...
data()}{
 return{
  countryTags:`<option value="BD">Bangladesh</option>`
 }
}
</script>

Since, here I can't render any extra html tag, I tired <template v-html="countryTags"> and that didn't worked. The other solution around stackoverlflow seems little confusing. what's the proper solution ?

Upvotes: 12

Views: 8287

Answers (1)

Reinhard Schnetzinger
Reinhard Schnetzinger

Reputation: 194

Unfortunately, Vue does not provide an easy way to accomplish this (More details about the reasons can be found here: https://github.com/vuejs/vue/issues/7431)

As explained there you can create a functional component to just render the HTML without a wrapper element:

Vue.component('html-fragment', {
  functional: true,
  props: ['html'],
  render(h, ctx) {
    const nodes = new Vue({
      beforeCreate() { this.$createElement = h }, // not necessary, but cleaner imho
      template: `<div>${ctx.props.html}</div>`
    }).$mount()._vnode.children
    return nodes
  }
})

This component is created by a Vue core member (LinusBorg): https://jsfiddle.net/Linusborg/mfqjk5hm/

Upvotes: 7

Related Questions