vue.js - 将动态插槽从父级传递到子级到孙子级
问题描述
有谁知道如何将动态插槽从父级传递给孙子级?
我知道如何使用静态命名插槽而不是动态命名插槽。
例如,假设插槽模板是父级中的“名称”,而孙子级具有基于动态列的插槽。
如何在孩子中添加模板以将其传递下去。
这是我的代码示例:
// 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>
任何帮助表示赞赏。
解决方案
我已经解决了。我会回答我自己的问题,以防将来可以帮助其他人。
为了连接父母和孙子,我将以下内容放在中间组件中(在我的情况下为 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>
推荐阅读
- javascript - 更改每个文件或每个 describe() 块的 mocha 选项
- node.js - NodeJS + Google Login + Firebase Functions 导致解码 Firebase 会话 cookie 失败
- api - 未找到 PUT 方法 appscript api 密钥
- json - Json 多参数如何解析?
- javascript - 将 Array.from 作为回调传递给 Array.flatMap 时,为什么会出现 TypeError: 0 is not a function?
- google-play - 从变量设置 DevOps 任务下拉选项
- javascript - 组件列表:函数没有收到正确的参数
- reactjs - 测试 Window.Location.Pathname 测试库 + jest
- spring - 使用 Spring Authorization Server 配置 Spring Gateway
- sql - 如果包含某些字符串 postgres 则拆分文本