有人知道如何将动态广告位从父级传递到孙级吗?
我知道如何使用静态命名槽,而不使用动态命名槽。
例如,假设广告位模板在父级中为“名称”,而孙子级具有基于动态列的广告位。
如何在子级中添加模板以将其传递下来。
这是我的代码示例:
// GrandChild.vue
<template>
<table>
<tbody>
<template v-for="(item, itemIndex) in items">
<tr :key="itemIndex">
<template v-for="(col, colIndex) in columns">
<slot
v-if="$scopedSlots[col]"
:name="col"
:item="item"
/>
<td
v-else
:key="colIndex"
>
{{ String(item[col]) }}
</td>
</template>
</tr>
</template>
</body>
</table>
</template>
<script>
export default {
props: ['items', 'columns']
}
</script>
// Child.vue
<template>
<grand-child :items="items" :columns="columns">
<!-- not sure what goes here -->
</grand-child>
</template>
<script>
export default {
props: ['items', 'columns']
}
</script>
// Parent.vue
<template>
<child :items="items" :columns="columns">
<template #name="{item}">
<td>Name is {{ item.name }}</td>
</teamplate>
</child>
</template>
<script>
export default {
data () {
return {
items: [
{id: 1, name: 'Item 1'},
{id: 2, name: 'Item 2'},
{id: 3, name: 'Item 3'},
{id: 4, name: 'Item 4'}
],
columns: ['id', 'name']
}
}
}
</script>
任何帮助表示赞赏。
答案 0 :(得分:1)
我已经解决了。我会回答我自己的问题,以防将来对其他人有帮助。
为弥合父母和孙辈,我将以下内容放入中间组件(在我的情况下为Child.vue)
<template v-for="field in Object.keys($scopedSlots)" v-slot:[field]="{item}">
<slot :name="field" :item="item"/>
</template>
完整代码:
// Child.vue
<template>
<grand-child :items="items" :columns="columns">
<template v-for="field in Object.keys($scopedSlots)" v-slot:[field]="{item}">
<slot :name="field" :item="item"/>
</template>
</grand-child>
</template>
<script>
export default {
props: ['items', 'columns']
}
</script>