如何在Nuxt3的Storybook中渲染动态插槽组件
解决Vue动态命名插槽在Storybook中的渲染问题
问题描述
我有如下所示的动态命名插槽组件代码:
<div> <template #middle> <slot :name="`middle-${index}`" /> </template> </div>
我想要在Storybook中渲染该组件,但不清楚如何设置模板来实现。以下代码无法正常运行,请问该如何解决?
template: ` <StoryComponent v-bind="args"> <template v-for="(content, index) in args.middle" :key="index" :slot="'middle-' + index" // 想正确设置插槽名称 > {{content}} </template> </StoryComponent> `,
解决方案
问题出在插槽的绑定语法上:你使用的是Vue 2的:slot语法,但组件代码采用的是Vue 3的插槽写法(#middle是Vue 3的插槽缩写),Vue 3中动态命名插槽需要使用动态v-slot语法,即v-slot:[动态名称]或其缩写#[动态名称]。
修改后的Storybook模板代码如下:
缩写写法(推荐)
template: ` <StoryComponent v-bind="args"> <template v-for="(content, index) in args.middle" :key="index" #[`middle-${index}`] > {{content}} </template> </StoryComponent> `,
完整写法
template: ` <StoryComponent v-bind="args"> <template v-for="(content, index) in args.middle" :key="index" v-slot:[`middle-${index}`] > {{content}} </template> </StoryComponent> `,
额外注意事项
- 确保
args.middle是一个包含插槽内容的数组,例如配置args: { middle: ['插槽内容1', '插槽内容2'] } - 组件内部的
index变量必须已定义(比如组件中有循环生成middle-${index}插槽的逻辑,要保证index的存在)
内容的提问来源于stack exchange,提问作者user16589580
相关产品推荐
相关产品推荐

