首页 > 解决方案 > 将动态插槽从父级传递到子级到孙子级

问题描述

有谁知道如何将动态插槽从父级传递给孙子级?

我知道如何使用静态命名插槽而不是动态命名插槽。

例如,假设插槽模板是父级中的“名称”,而孙子级具有基于动态列的插槽。

如何在孩子中添加模板以将其传递下去。

这是我的代码示例:

// 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>

任何帮助表示赞赏。

标签: vue.jsvue-component

解决方案


我已经解决了。我会回答我自己的问题,以防将来可以帮助其他人。

为了连接父母和孙子,我将以下内容放在中间组件中(在我的情况下为 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>

推荐阅读