【发布时间】:2021-01-20 14:07:01
【问题描述】:
Vue 对象有一个非常有用的成员,叫做$attrs。 $attrs 所做的是包含所有未被识别为当前组件道具的属性。 $attrs 的一个很好的例子是 here。
我想知道$attrs 是否有对应于$scopedSlots 的等价物。我目前正在使用类似于 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 不会被绑定两次,但mySlot 将被发送到wrapper 和b-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>
想知道是否有更好的方法来做到这一点。谢谢!
【问题讨论】:
标签: javascript vue.js vuejs2 vue-component