Vue 2: How to render Single File Components from Render Functions?

Viewed 6049

I'm trying to render a Single File Vue Component from a render function but it isn't being created. I tried variations similar to:

// simple.vue
<template>
...
</template>
<script>
 ...
</script>

// parent.vue
<script>
import Simple from 
export default {
  name: "parentComponent",
  render: function (h) {
    return h(
      "div",
      null,
      Simple  // [Simple], Vue.component(Simple)
  }
}
</script>

How can I build Vue components from render functions? If it makes a difference I'm also using pug.

1 Answers

If I understand correctly, you simply want to render components that may be written as single file components from a render function. This is easy to do.

Let's assume I have the following single file component.

Child.vue

<template>
  <h1>This is the Child component</h1>
</template>

And I want to render that from a component that uses a render function. Here is an example that does that.

Parent.js

import Child from "./Child.vue"

export default {
  render(h){
    return h("div", ["Text in Parent", h(Child)])
  },
  components: {Child}
}

Here is a working example.

The important parts to note is that when you want to render a component, you simply pass the component definition as the first argument to the createElement function (above aliased as h). This is what @Phil was pointing out in the comments. h(Child) creates a child component. Technically it creates a virtual node, which Vue uses to render an instance of the component.

All of this is covered well in the documentation.

Related