Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue component render function: print unescaped html entity

How can I make Vue 2 render my component without escaping the HTML entity and printing it as normal text? If it were a tag, I'd nest another createElement, but this is not the case.

Vue.component('my-component', {
  render: function(createElement) {
    return createElement('div', ' ')
  }
})

new Vue({
  el: '#app',
  components: [
    'my-component'
  ]
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.min.js"></script>

<div id="app">
  <my-component />
</div>
like image 781
Tomas Buteler Avatar asked Nov 01 '25 12:11

Tomas Buteler


1 Answers

You can define DOM properties and HTML attributes in the second argument of createElement function.

Docs: https://v2.vuejs.org/v2/guide/render-function.html#The-Data-Object-In-Depth

Solution:

Vue.component('my-component', {
  render: function(createElement) {
    return createElement('div', {
        domProps: {
          innerHTML: '&nbsp;'
        }
    })
  }
})

new Vue({
  el: '#app',
  components: [
    'my-component'
  ]
})

console.log(document.getElementById('app').firstChild.innerHTML)
<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="app">
  <my-component></my-component>
</div>

Update after comment:

you can populate your component with children like this:

Vue.component('my-component', {
  render: function(createElement) {
    return createElement('div', 
    [
      createElement('p', 'top tag'),
      createElement('div', {
        domProps: {
            innerHTML: 'A&nbsp;B'
          }
      }),
      createElement('p', 'bottom tag'),
    ]
    )
  }
})

new Vue({
  el: '#app',
  components: [
    'my-component'
  ]
})

console.log(document.getElementById('app').firstChild.innerHTML)
<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="app">
  <my-component></my-component>
</div>
like image 123
Egor Stambakio Avatar answered Nov 04 '25 13:11

Egor Stambakio