Vue - How to render HTML in vue components
Asked Answered
R

3

30

This is what I'm trying to accomplish:

{{ span('Hello') }}

And what desired output should be is:

<span>
   Hello
</span>

Is this possible?

Thanks

Roper answered 4/7, 2019 at 6:40 Comment(4)
Obviously possible, but can you share what you have tried yet?Seer
You should use JSX to display for this purpose! Follow here scotch.io/tutorials/using-jsx-with-vue-and-why-you-should-careUnderpinning
@SatyamPathak well, what I really want to accomplish is that, when a certain configuration is turned on, the method needs to add a 'span' or a 'button' around it so I can click on it.Roper
That looks like something you fundamentally avoid doing! People need to understand your method, and the overall result obscures what's going on.Nurmi
S
62

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>
Seer answered 4/7, 2019 at 7:29 Comment(1)
Thanks. I didn't know you could not render HTML in the brackets. Used your solution to continueRoper
G
8

For Vue3 it is v-html="htmlContent"

Gotha answered 27/11, 2022 at 16:35 Comment(2)
See "How to Answer" and Explaining entirely code-based answers". While this might be technically correct, it doesn't explain why it solves the problem or should be the selected answer. We should educate along with helping solve the problem.Pericranium
Thanks for the suggestion @theTinMan. I will keep this in mind next time and I will also edit the above answer :)Gotha
R
3

<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'
    }
  }
})
Rocca answered 4/7, 2019 at 6:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.