Vue.js - 从过滤的scopedSlots动态创建槽

stu*_*-pj 5 javascript vue.js vue-component vuejs2 vuetify.js

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

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

父.vue:

<Child>
    <template #table--item.person_id="{ value }">
        <div class="text-caption">{{ value }}</div>
    </template>
</Child>
Run Code Online (Sandbox Code Playgroud)

孩子.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>
Run Code Online (Sandbox Code Playgroud)

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

Dan*_*Dan 1

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

key.replace(prefix, "")
Run Code Online (Sandbox Code Playgroud)

父级无法访问子插槽,因为父级的目标名称的前缀仍然完好无损。

更改子组件中的插槽:

key.replace(prefix, "")
Run Code Online (Sandbox Code Playgroud)