【问题标题】:Passing dynamic slots down from parent to child to grandchild将动态插槽从父级传递到子级到孙子级
【发布时间】:2020-10-08 02:14:34
【问题描述】:

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

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

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

我如何在孩子中添加一个模板来传递这个。

这是我的代码示例:

// 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.js vue-component


    【解决方案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>
    

    【讨论】:

      猜你喜欢
      • 2021-05-12
      • 2017-12-24
      • 2020-09-09
      • 1970-01-01
      • 2016-08-09
      • 2018-09-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多