如何在Storybook v7 Beta中正确处理Vue 3的Slots?
Storybook v7 Beta + Vue3 插槽优化实现方案
一、简化插槽写法的方案
方案1:利用Storybook原生插槽支持(推荐)
Storybook v7对Vue3的插槽支持已做优化,无需手动拼接模板字符串,可直接在args中定义插槽内容,并通过argTypes声明插槽字段,支持在Storybook控制面板编辑:
import { Meta, StoryObj } from '@storybook/vue3'; import Modal from './Modal.vue'; // 扩展组件Props类型,纳入插槽相关字段 type ModalProps = typeof Modal['props'] & { data?: string; // 对应data插槽的HTML内容 }; const meta: Meta<ModalProps> = { title: 'Componenten/Modal', component: Modal, argTypes: { data: { control: 'text', description: 'Data插槽内容', }, }, render: (args) => ({ components: { Modal }, setup() { return { args }; }, template: ` <Modal v-bind="args"> <template v-slot:data v-if="args.data"> <div v-html="args.data"></div> </template> </Modal> `, }), }; export default meta; type Story = StoryObj<ModalProps>; export const Default: Story = { args: { title: 'Are you sure?', show: true, actions: [ { buttonType: 'Remove', label: 'Yes, remove', link: () => {}, }, { label: 'Cancel', link: () => {}, }, ], data: '<a href="/test">Hello world</a>', }, };
方案2:使用Vue的h函数渲染插槽
若需渲染组件而非HTML字符串这类复杂插槽内容,可直接用Vue的h函数构建插槽,完全规避模板拼接:
import { h } from 'vue'; import { Meta, StoryObj } from '@storybook/vue3'; import Modal from './Modal.vue'; import TestLink from './TestLink.vue'; const meta: Meta<typeof Modal> = { title: 'Componenten/Modal', component: Modal, render: (args) => h(Modal, args, { // 直接传递插槽内容,支持组件、VNode或字符串 data: () => h(TestLink, { href: '/test' }, 'Hello world'), }), }; export default meta; type Story = StoryObj<typeof Modal>; export const WithComponentSlot: Story = { args: { title: 'Are you sure?', show: true, actions: [/* ... */], }, };
二、TypeScript类型错误解决
要规避any类型并解决TS2322错误,需将插槽字段纳入类型定义,以下两种方法可选:
方法1:扩展组件Props类型
提取组件原有Props类型,手动添加插槽相关字段:
import type { ComponentProps } from 'vue'; import Modal from './Modal.vue'; // 自定义包含插槽字段的类型 type ModalStoryProps = ComponentProps<typeof Modal> & { data?: string; // 对应data插槽的HTML内容 // 其他插槽字段可在此补充 }; // 在meta中使用扩展后的类型 const meta: Meta<ModalStoryProps> = { // ... 配置内容 };
方法2:通过argTypes声明类型
在argTypes中明确插槽字段的类型,让TypeScript识别其属于args的合法属性:
const meta: Meta<typeof Modal> = { title: 'Componenten/Modal', component: Modal, argTypes: { data: { type: 'string', control: 'text', }, } as const, // 固定argTypes类型,让TypeScript识别字段 // ... };
内容的提问来源于stack exchange,提问作者Olivier Van Bulck
相关产品推荐
相关产品推荐

