How can i render the result of createElement() in Vue.js without creating a component

4.6k Views Asked by At

My goal is to build a test suite to visualize the differences of implementation of the inner hyperscript method createElement() (otherwise known as h()) within React, preact, Inferno, Snabbdom, Vue..

In React, i can invoke it like that (without building a component) :

ReactDOM.render(
  React.createElement('div', { className: 'preview' }, ['Hello World']),
  document.getElementById('react-preview')
)

In Preact, we simply do :

preact.render(
  preact.h('div', { className: 'preview' }, ['Hello World']),
  document.getElementById('preact-preview')
)

With Inferno.. i must import inferno and inferno-hyperscript :

Inferno.render(
  Inferno.h('div', { className: 'preview' }, ['Hello World']),
  document.getElementById('inferno-preview')
)

Now, i'm still trying to figure how to do this in Vue without creating a component : i don't want to deal with the additional cost of components instances creation, i just want to visualize and compare the raw virtual dom creation and rendering process of each library.

I have found a way to do it in this post, but it still create a new Vue instance..

new Vue({
 render: h => h('div', { className: 'preview' }, ['Hello World'])
}).$mount('#vue-preview')
3

There are 3 best solutions below

1
On BEST ANSWER

This is something that is not usually done in the Vue world, and because the way Vue "listens" to variable changes, it by default comes with an instance that actually does the listening.

This is the major difference between Vue and other frameworks, where in other frameworks you need to call the render function manually, Vue modifies the original objects and watches on them.

If you are only interested in the final DOM structure, just destroy the Vue object once you are done.

new Vue({
    render: h => h('div', { className: 'preview' }, ['Hello World'])
}).$mount('#vue-preview').$destroy()
7
On

Quick way is to access the render method.

var app = new Vue({
  el: '#app',
data() {
    return {
      isRed: true
    }
  },

  /*
   * Same as
   * <template>
   *   <div :class="{'is-red': isRed}">
   *     <p>Example Text</p>
   *   </div>
   * </template>
   */
  render(h) {
    return h('div', {
      'class': {
        'is-red': this.isRed
      }
    }, [
      h('p', 'Example Text')
    ])
  }
})
0
On

You have to use slots for this:

https://v2.vuejs.org/v2/guide/components-slots.html