Vue2:如何从渲染函数中渲染单文件组件?

8

我正在尝试使用渲染函数渲染单文件Vue组件,但是它没有被创建。我尝试过类似于以下的变化:

// 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>

我如何通过渲染函数构建Vue组件?如果使用pug会有什么不同吗?


2
我不明白。如果你有一个渲染函数,那么就不需要一个单文件组件了。 - Bert
vue-cli webpack 模板中的示例使用 render: h => h(Simple) - Phil
@Bert 基本上我的使用情况是,我有一个组件需要(或已经编写)渲染函数,但它的子组件不需要。继续在渲染函数中编写这些内容比使用模板更加繁琐。 - writofmandamus
@Phil 嗯,我在vue-cli的主要自述文件中没有看到它。你有链接吗?你如何传递props并指定其他属性? - writofmandamus
1个回答

3
如果我理解正确,您只需要从渲染函数中呈现可能编写为单文件组件的组件。这很容易做到。
假设我有以下单文件组件。
Child.vue
<template>
  <h1>This is the Child component</h1>
</template>

我希望从使用渲染函数的组件中呈现它。这里有一个执行此操作的示例。

Parent.js

import Child from "./Child.vue"

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

这里有一个可运行示例

需要注意的重要部分是,当你想要渲染一个组件时,只需将组件定义作为第一个参数传递给createElement函数(别名为h)。这就是Phil在评论中指出的。 h(Child)创建了一个子组件。严格来说,它创建了一个虚拟节点,Vue用于渲染组件实例。

这些都在文档中很清楚地介绍了。


好的,我只是有点傻,实际上已经在做这个了,但是在将子组件导入到“components”对象中后,将其分解为h('child-component-name', { ... }) - writofmandamus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接