You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js 3中如何将组件的option插槽内容默认传递给主插槽且支持重写?

Vue.js 3中如何将组件的option插槽内容默认传递给主插槽且支持重写?

嘿,咱们来好好捋下这个问题的来龙去脉和解决办法:

你有一个名为Foo的组件,初始结构是这样的:

<Bar>
  <template #option="slotProps" v-if="$slots.option">
    <slot name="option" v-bind="slotProps"></slot>
  </template>
</Bar>

<div>
  <slot :selected="selectedOption"></slot>
</div>

你的需求是:让主插槽<slot :selected="selectedOption"></slot>默认复用option插槽的内容,但同时保留外部重写主插槽的灵活性。

你一开始尝试了下面的写法,但没成功:

<slot :selected="selectedOption">
  <template v-if="$slots.option">
    <slot name="option" :selected="selectedOption"></slot>
  </template>
</slot>

不过你很快就通过一个小修改搞定了!调整后的代码如下:

<slot :selected="selectedOption">
  <template v-if="$slots.option">
    <slot name="option" :option="selectedOption"/>
  </template>
</slot>

这里的关键其实是插槽绑定的参数名要对应上:原来的option插槽在Bar组件中接收的是名为option的参数(也就是slotProps里的option属性),你之前在主插槽默认内容里传的是:selected="selectedOption",参数名不匹配,所以option插槽没法正确渲染内容;改成:option="selectedOption"后,参数名和option插槽预期的一致了,它就能正常接收并渲染内容。

这样一来,主插槽在没有外部自定义内容时,就会自动把option插槽的内容作为默认值;如果外部需要重写主插槽,直接在使用Foo组件时编写主插槽的自定义内容就行,完全不会冲突~

备注:内容来源于stack exchange,提问作者armandino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.13 20:17:56