Vue.js VueJS:在安装组件之前,使用组件分析插槽的内容
假设我们有一个组件Vue.js VueJS:在安装组件之前,使用组件分析插槽的内容,vue.js,vuejs2,vue-component,Vue.js,Vuejs2,Vue Component,假设我们有一个组件 使用这种模板: <div class="container"> <slot></slot> <my-cp2 v-for="li in list" :my-data="li.data"></my-cp2> </div> 我试图在安装插槽之前分析插槽的内容,但似乎只有在子组件已安装之后,我才能访问该元素。将默认内容放入组件的插槽中。如果用户添加插槽内容,将显示其内容。否则,将显示插槽内容 <
使用这种模板:
<div class="container">
<slot></slot>
<my-cp2 v-for="li in list" :my-data="li.data"></my-cp2>
</div>
我试图在安装插槽之前分析插槽的内容,但似乎只有在子组件已安装之后,我才能访问该元素。将默认内容放入组件的插槽中。如果用户添加插槽内容,将显示其内容。否则,将显示插槽内容
<div class="container">
<slot>
<my-cp2 v-for="li in list" :my-data="li.data"></my-cp2>
</slot>
</div>
这是一个。您的意思是,如果有人提供了默认的插槽内容作为备用,您想使用它吗?完全正确!谢谢你的翻译:)对不起,不是“默认为备用”,而是“作为备用”。我的意思是插槽没有默认内容,但如果提供了内容,则应将其用作fallbackYes,但在装入插槽后,我将无法在列表中添加元素。目标是将v-for保持在列表中。插槽仅用于初始化,但一旦装入,我希望通过在列表数组中推送新元素来保持添加新元素的可能性。@Nabab您的意思是,在某些情况下,您可能无法将
list
作为属性,而希望从插槽的内容对其进行初始化?这正是正确的that@Nabab让我想想。您可以使用this.$slots.default
(如果不是命名插槽)访问插槽中的内容。从那里你可以看到节点,但我想你最终会自己解析它。@Nabab我已经更新了答案。我想这是你想要的方式。
<div class="container">
<slot>
<my-cp2 v-for="li in list" :my-data="li.data"></my-cp2>
</slot>
</div>
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])
},
})