如何将Fallthrough属性绑定到一个插槽?

huangapple go评论116阅读模式
英文:

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>

huangapple
  • 本文由 发表于 2023年6月5日 04:23:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76402265.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定