【问题标题】:Vuejs - How to render vnodes of child components when using slotsVuejs - 使用插槽时如何渲染子组件的 vnode
【发布时间】:2018-01-09 02:34:33
【问题描述】:

如何从其子组件的父组件渲染 vnode。 我有一个渲染函数,它循环遍历 this.$slots.default 中的一组子项。目的是将孩子包装在 li 标签中。

问题是子组件不渲染,我得到空的 li 标签。我在这里缺少什么以及在文档中的哪里可以找到解决方案。 The Fiddle Can be found here 嵌入代码如下。

// Parent component
const MyParent = Vue.component('my-parent', {

  render: function(createElement) {
    var parentContent = createElement('h2', "These are Parent's Children:")
    var myChildren = this.$slots.default.map(function(child) {
      //console.log("Child: ", child)

      return createElement(
        'li',
        child
      )
    })

    var content = [].concat(parentContent, myChildren)

    return createElement(
      'div', {},
      content
    )
  }

});


// Child Component
const MyChild = Vue.component('my-child', {
  template: '<h3>I am a child</h3>'
});



// Application Instance
new Vue({
  el: '#app',
  components: {
    MyParent,
    MyChild
  }
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="app">
  <my-parent>
    <my-child></my-child>
    <my-child></my-child>
  </my-parent>

</div>

【问题讨论】:

标签: vue.js vuejs2


【解决方案1】:

createElement 接受一个 vnode 数组。 它应该像这样工作:

return createElement(
   'li',
   [child]) 
}) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-09
    • 2019-10-14
    • 2018-12-06
    • 2020-05-02
    • 2020-11-15
    • 2019-08-19
    • 2017-12-06
    • 2019-03-07
    相关资源
    最近更新 更多