【问题标题】:Vue.js - Dynamically create slots from filtered scopedSlotsVue.js - 从过滤的 scopedSlots 动态创建插槽
【发布时间】:2021-04-23 05:35:32
【问题描述】:

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

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

Parent.vue:

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

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

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component vuetify.js


    【解决方案1】:

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

    key.replace(prefix, "")
    

    父级无法访问子槽,因为父级定位的名称前缀仍保持不变。

    更改子组件中的插槽:

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

    【讨论】:

    • 感谢您的回复。但我认为你误解了这个问题。当然,如果您省略 table-- 并删除计算属性中的所有逻辑,它会起作用。但是我怎么才能在 Child.vue 中的特定位置只渲染表格 - 插槽?
    • 我会尽量明确一点:v-data-table 确实需要一个名为 item.glutenfree 的插槽。但是,table-- 前缀只是为了让我可以在特定位置呈现以 table-- 为前缀的插槽。
    • 我可能有。尽管如此,孩子创建了一个没有前缀的插槽名称,而父母无法使用前缀访问。所有列都会被定位吗?如果没有,当列槽没有被定位时,您希望发生什么?
    • 在 App.vue 中,我们调用 genericTable 组件并将一个名为 table--item.glutenfree 的插槽传递给它。现在,在genericTable.vue 组件中,我们可以通过this.$scopedSlots 访问这个插槽。计算属性tableSlots()this.$scopedSlots 转换为以table-- 开头的所有槽的过滤版本。一旦我们有了这些插槽,我们就可以删除前缀,以便它在&lt;v-data-table&gt; 中具有正确的插槽名称。我认为它在做正确的事情,正如您在我插入挂载钩子的 console.log 中看到的那样。然而,它不起作用......
    • 它在定位v-data-table 时会使用正确的名称,但它也会使用过滤后的名称创建一个槽供父级定位,但父级使用前缀。你需要这个:&lt;slot :name="'table--' + slotName" v-bind="scope"&gt;&lt;/slot&gt;。我更新了我的答案以使这一点更清楚。
    猜你喜欢
    • 1970-01-01
    • 2018-10-13
    • 2019-03-12
    • 2021-11-25
    • 2020-06-05
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多