Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 907
Kevin Gorjan Avatar asked Jul 04 '19 06:07

Kevin Gorjan


People also ask

How do I render components in Vue?

Each Vue component implements a render function. Most of the time, the function will be created by the Vue compiler. When you specify a template on your component, the content of this template will be processed by the Vue compiler that will return a render function.

How do I use Vue component in HTML?

Vue. component('testcomponent',{ template : '<div><h1>This is coming from component</h1></div>' }); var vm = new Vue({ el: '#component_test' }); var vm1 = new Vue({ el: '#component_test1' }); In the . html file, we have created two div with id component_test and component_test1.

Does Vue compile to HTML?

vue-template-loader compiles HTML into individual render functions in the respective TypeScript or JavaScript files.

Can I use JSX in Vue?

If you have worked with JSX before, do note that Vue JSX transform is different from React's JSX transform, so you can't use React's JSX transform in Vue applications. Some notable differences from React JSX include: You can use HTML attributes such as class and for as props - no need to use className or htmlFor .


2 Answers

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>
like image 167
Satyam Pathak Avatar answered Oct 03 '22 12:10

Satyam Pathak


<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'
    }
  }
})
like image 38
Puwka Avatar answered Oct 03 '22 12:10

Puwka