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

1

8

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.

Westphal answered 21/11, 2017 at 1:43 Comment(4)
I don't understand. If you have a render function, there's no need for a single file component.Bibliology
The example in the vue-cli webpack template uses render: h => h(Simple)Appointor
@Bibliology Basically my use case is I have a component that requires (or is already written in) the render functions, but its child components do not need to be. It would be more cumbersome to continue writing those in render functions as opposed to a template.Westphal
@Appointor Hmm, I don't see it on vue-cli's main readme. Do you have a link? How would you pass down props and specify other attributes?Westphal
B
3

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.

Bibliology answered 21/11, 2017 at 15:34 Comment(2)
Okay I was just being stupid and was actually already sort of doing this, but broke it up like h('child-component-name', { ... }) after putting the child component import into the components object.Westphal
how to pass prop to Child component?Pily

© 2022 - 2024 — McMap. All rights reserved.