英文:
How to bind Fallthrough Attributes to a slot?
问题
我希望通过使用Fallthrough组件来使代码更加简洁,如下所示:
<Fallthrough class="class-a">
<ComponentA v-if="cond" />
<ComponentB class="class-b" v-else />
</Fallthrough>
而Fallthrough组件的定义如下:
<script>
export default {
inheritAttrs: false,
};
</script>
<template>
<slot v-bind="$attrs"></slot>
</template>
我期望这段代码能够工作,但不幸的是它并没有(属性没有传递)。我已经多次检查过,如果将slot切换为div,那么v-bind="$attrs"是有效的,所以slot明显是问题所在。请您帮助我解决这个问题。
英文:
Say, I have the following template:
<ComponentA class="class-a" v-if="cond" />
<ComponentB class="class-a class-b" v-else />
I'd want to dry the code by using some Fallthrough component like this:
<Fallthrough class="class-a">
<ComponentA v-if="cond" />
<ComponentB class="class-b" v-else />
</Fallthrough>
, whereas the Fallthrough component is defined like this:
<script>
export default {
inheritAttrs: false,
};
</script>
<template>
<slot v-bind="$attrs"></slot>
</template>
I expect this code to work, but unfortunately, it does not (the attributes aren't passed). I've double checked that v-bind="$attrs" works if switching slot to div, so the slot is definitely the problem. Could you please help me?
答案1
得分: 2
尝试在插槽中作用域化$attrs,如下所示:
<script>
export default {
inheritAttrs: false,
};
</script>
<template>
<slot v-bind:attrs="$attrs"></slot>
</template>
然后像这样使用它们:
<Fallthrough class="class-a" v-slot="{attrs}">
<ComponentA v-if="cond" v-bind="attrs" />
<ComponentB class="class-b" v-else v-bind="attrs" />
</Fallthrough>
英文:
Try to scope the $attrs in the slot like :
<script>
export default {
inheritAttrs: false,
};
</script>
<template>
<slot v-bind:attrs="$attrs"></slot>
</template>
then use them like :
<Fallthrough class="class-a" v-slot="{attrs}">
<ComponentA v-if="cond" v-bind="attrs" />
<ComponentB class="class-b" v-else v-bind="attrs" />
</Fallthrough>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论