VueJS:在安装组件之前分析插槽的内容

VueJS: Analyze content of a slot with components before they are mounted

假设我们有一个组件 <my-cp :list="list"></my-cp>

使用这种模板:

<div class="container">
  <slot></slot> 
  <my-cp2 v-for="li in list" :my-data="li.data"></my-cp2>
</div>

我的问题:是否可以使用列表作为数组或使用 HTML 来初始化我的组件 my-cp

我的意思是两种可能性都有。在这种情况下,HTML 将如下所示:

<my-cp>
  <my-cp2 my-data="foo">
  <my-cp2 my-data="bar">
</my-cp>

我试图在安装之前分析插槽的内容,但似乎我只能在子组件已经安装后才能访问该元素。

将您的默认内容放在组件中的插槽中。如果用户添加插槽内容,他们的内容将显示。否则,插槽内容将显示。

<div class="container">
  <slot>
    <my-cp2 v-for="li in list" :my-data="li.data"></my-cp2>
  </slot> 
</div>

这是一个example

编辑

经过评论的进一步讨论,我相信我明白你想做什么了。为了向未来的读者澄清,据我所知,@Nabab 希望能够使用来自 属性 的数据或来自组件插槽中 HTML 中呈现的组件的数据来初始化他的组件.此外,该组件应该能够修改现有数据以将更多项目添加到其列表中。

您可以使用渲染函数执行此操作。

Vue.component("my-cp",{
  props:["list"],
  data(){
    return {
      internalList: this.list
    }
  },
  render(h){
    let workingList = []

    // Examine the default slot, and if there are any parse
    // them and add the data to the workingList
    if (this.$slots.default){
      for (node of this.$slots.default)
        // May want to check here if the node is a myCp2,
        // otherwise, grab the data
         workingList.push(node.componentOptions.propsData.myData)
    }

    // Add any items that came from the property/internal data
    workingList = workingList.concat(this.internalList)

    // Create a list of myCp2 vnodes with the correct data
    const list = workingList.map(n => h(myCp2, {props:{myData:n}}))

    // Create a button to add list items
    const btn = h("button", {on:{click:() => this.internalList.push({bar: true})}}, "Add")

    //Render
    return h("div", [list, btn])
  },
})

这是一个example