首页 > 解决方案 > Vue.js - 从过滤的 scopedSlots 动态创建插槽

问题描述

感谢 Vue.js Scoped Slots,我能够遍历子组件中的所有可用插槽。现在,我尝试做的是仅在模板中的特定位置呈现以某个字符串开头的插槽。

不幸的是,它不起作用。我可能忽略了一些东西。

父.vue:

<Child>
    <template #table--item.person_id="{ value }">
        <div class="text-caption">{{ value }}</div>
    </template>
</Child>

孩子.vue:

<template>
    <v-data-table>
        <template v-for="(_, slotName) of tableSlots" v-slot:[slotName]="scope">
            <slot :name="slotName" v-bind="scope"></slot>
        </template>
    </v-data-table>
</template>
<script>
    export default {
        computed: {
            tableSlots() {
                const prefix = 'table--';
                const raw = this.$scopedSlots;
                const filtered = Object.keys(raw)
                    .filter(key => key.startsWith(prefix))
                    .reduce((obj, key) => ({
                        ...obj,
                        [key.replace(prefix, "")]: raw[key]
                    }), {});
                return filtered;
            }
        }
    }
</script>

https://codesandbox.io/s/keen-bose-yi8x0

标签: javascriptvue.jsvuejs2vue-componentvuetify.js

解决方案


父级尝试访问一个名为的插槽table--item.glutenfree,因此使用该名称创建了一个作用域插槽。但是,当您过滤以定位相应的v-data-table插槽时,您还可以将过滤后的名称用于子插槽:

key.replace(prefix, "")

父级无法访问子槽,因为父级定位的名称前缀仍完好无损。

更改子组件中的插槽:

<slot :name="`table--${slotName}`" v-bind="scope"></slot>

推荐阅读