4

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>

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, excellent, that does the trick. But what if there are other children inside the same element? The innerHTML doesn't play nice with other elements...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.