Kevin Gorjan
Kevin Gorjan

Reputation: 1332

Vue - How to render HTML in vue components

This is what I'm trying to accomplish:

{{ span('Hello') }}

And what desired output should be is:

<span>
   Hello
</span>

Is this possible?

Thanks

Upvotes: 33

Views: 98475

Answers (3)

Satyam Pathak
Satyam Pathak

Reputation: 6932

Look at the below snippet -

Note - You can't render html inside {{ }} because it get added to text node of the element. To render it as an html you need to use v-html and have your function which return element wrapping your text

new Vue({
  el: "#app",
  data: {
    foo: 'asdasd'
  },
  methods: {
   span(text) {
    return `<span> ${text} </span>`
   }
  }
})
span {
 color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>


<div id="app">
  <h1> 
    Render whatever you want
  </h1>
  <div v-html="span('Hello world')" /> 
</div>

Upvotes: 65

Rahimuddin
Rahimuddin

Reputation: 614

For Vue3 it is v-html="htmlContent"

Upvotes: 8

Puwka
Puwka

Reputation: 650

<span>{{Hello}}</span>

If you need dynamic HTML tag <tag :is="tag">{{Hello}}</tag>

Vue.component('tag', {
  props:{
     is:{type:String, required:true}
  },
  render(h){
    return h(this.tag, this.$slots.default)
  }
})
new Vue({
    el:'#vue',
    data(){
    return {
        tag:'h1'
    }
  }
})

Upvotes: 3

Related Questions