我想将X数量的组件传递到插槽中并循环通过它们。像这样...
<Foo>
<template #abc>
<Bar />
<Bar />
<Bar />
</template>
<template #def>Baz</template>
</Foo>
Foo.vue
<template>
<v-container>
<v-row>
<v-col v-for="child in $children" :key="child">
<slot name="abc"></slot>
</v-col>
</v-row>
<v-row>
<v-col>
<slot name="def"></slot>
</v-col>
</v-row>
</v-container>
<template>
我觉得我与语法非常接近,但是我不确定这是否可行。我在正确的轨道上吗?我知道插槽中有一个this。$ children,但是我不确定如何通过模板在其中查找组件。
答案 0 :(得分:0)
我知道实现此目标的唯一方法是使用render
函数。在render
函数中,您可以操纵该插槽的子VNode数组。
下面的示例在每对子代之间插入一个额外的项目。通过检查tag
来过滤掉文本节点和注释节点。
const MyList = {
render (h) {
const slot = this.$slots.default || []
const children = []
for (let index = 0; index < slot.length; ++index) {
const child = slot[index]
// Ignore
if (child.tag) {
if (index) {
children.push(h('div', null, ['Between']))
}
children.push(child)
}
}
return h('div', null, children)
}
}
new Vue({
el: '#app',
components: {
MyList
}
})
<script src="https://unpkg.com/vue@2.6.10/dist/vue.js"></script>
<div id="app">
<my-list>
<div>Item 1</div>
<div>Item 2</div>
<div v-if="false">Hidden</div>
<div>Item 3</div>
</my-list>
</div>
据我所知,模板仅允许您整体包含广告位的内容,而不能访问各个子级。