gpt4 book ai didi

javascript - 视觉 : wrapper for slots ignoring already-defined slots

转载 作者:行者123 更新时间:2023-12-03 06:41:13 26 4
gpt4 key购买 nike

Vue 对象有一个非常有用的成员,叫做 $attrs。什么$attrs does 包含所有未被识别为当前组件 props 的属性。 $attrs 的一个很好的例子是 here .

我想知道 $scopedSlots 是否有 $attrs 的等效项。我目前使用的方法类似于 https://stackoverflow.com/a/50892881/6100005 中的第一个建议。 . $scopedSlots 的问题在于它还传递了已定义的插槽。要在此处使用该示例:


<template>
<wrapper>
<b-table :foo="foo" v-bind="$attrs" v-on="$listeners">
<template v-for="(_, slot) of $scopedSlots" v-slot:[slot]="scope"><slot :name="slot" v-bind="scope"/></template>
</b-table>
<slot name="mySlot"></slot>
</wrapper>
</template>

<script>
export default {
props: {
// let's pretend that `b-table` has a prop `foo` that is default `false`
foo: {
type: boolean,
default: true,
}
}
}
</script>

现在,由于 $attrs 的行为,foo 不会被绑定(bind)两次,但是 mySlot 将被发送到两个 wrapperb-table

那么我如何才能将所有插槽传递给除了我正在定义自己的插槽

我的一个想法是拥有

computed: {
bTableSlots() {
Object.keys(this.$scopedSlots)
.filter( key => key!=='mySlot' )
.reduce( (res, key) => (res[key] = this.$scopedSlots[key], res), {} );
}
}

然后

        <template v-for="(_, slot) of bTableSlots" v-slot:[slot]="scope"><slot :name="slot" v-bind="scope"/></template>

想知道是否有更好的方法来做到这一点。谢谢!

最佳答案

那么除了我自己定义的插槽之外,如何传递所有插槽?

为什么这甚至是一个问题?如果<b-table>没有名称为 mySlot 的命名插槽, 它只会忽略它 - 最后它只是其中的一个条目 $scopedSlots组件永远不会访问的属性。而且由于作用域插槽作为函数传递,您无需支付任何额外的费用。

当 Vue 编译器看到插槽中的内容 ( <template #slotName> ) 时,它会将内容编译成 Array 。的 VNode s 或函数返回 ArrayVNode s 并将其传递给子组件。事实上,您的子组件将其进一步向下传递不会产生任何额外成本。它是对现有数组的引用或对现有函数的引用(对于作用域插槽),在这两种情况下,如果更下方的组件不知 Prop 有完全相同名称的插槽,则没有额外费用,除了在 $scopedSlots 中还有一项...

如果您觉得这是一个问题,恐怕过滤是唯一的方法 - 您可以按照自己的方式或通过一些辅助数组 [ 'slot1', 'slot2' ]定义所有现有的 b-table插槽并过滤其他所有内容(恕我直言,每次 b-table 添加新插槽时都需要更新组件)...

我理解这个想法并看到与 $attrs 的相似之处- 可能有类似 $unknownSlots 的东西在组件上保存当前组件未定义的插槽,但现在 Vue 公共(public) API 中没有类似的东西......

关于javascript - 视觉 : wrapper for slots ignoring already-defined slots,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64213179/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com