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

Vue3与Storybook 7中如何复用故事传组件至插槽?

解决Storybook Vue3中复用已有故事参数传入插槽组件的问题

你遇到的Error: Unexpected identifier 'Object'是因为直接在模板字符串中插入对象${disabledArgs}时,对象会被转为字符串[object Object],导致Vue模板解析语法错误。下面提供两种可行的解决方法:

方案一:将复用的参数挂载到setup中(推荐)

把要复用的Button故事参数挂载到组件的setup函数返回值里,然后在插槽模板中直接引用这个变量,避免对象转字符串的问题:

// 导入你需要复用的Button故事
import { DisabledButton } from '../Clickable/Button.stories'
import type { Meta, StoryObj } from '@storybook/vue3'
import UICard from './Card.vue'
import UIButton from '~/components/Clickable/Button.vue'
import { setDefaultProps } from '~/.storybook/utils'

// ... 省略meta和Playground故事定义 ...

export const ButtonAsSlot: Story = {
  ...Playground,
  story: {
    name: 'Button as slots',
  },
  render: (args, { argTypes }) => ({
    components: { UICard, UIButton },
    props: Object.keys(argTypes),
    setup() {
      // 把复用的Button参数挂载到setup中
      const buttonArgs = DisabledButton.args
      return {
        ...args,
        buttonArgs
      }
    },
    template: `
      <UICard v-bind="args">
        <template v-if="$props.default" v-slot>
            <p>↓Content of slot displayed below</p>
            ${args.default}
        </template>
      </UICard>
    `,
  }),
  args: {
    ...Playground.args,
    // 直接引用setup中定义的buttonArgs变量
    default: '<UIButton v-bind="buttonArgs" />',
  },
}

方案二:将参数序列化为JSON字符串

把复用的参数转为JSON字符串,在模板中通过JSON.parse解析后传给v-bind,注意要转义字符串中的单引号避免语法冲突:

import { ImportedStory } from '../Clickable/Button.stories'
// ... 省略其他导入和定义 ...

const disabledArgs = ImportedStory.args

export const ButtonAsSlot: Story = {
  ...Playground,
  story: {
    name: 'Button as slots',
  },
  render: (args, { argTypes }) => ({
    components: { UICard, UIButton },
    props: Object.keys(argTypes),
    setup() {
      return {
        ...args,
      }
    },
    template: `
      <UICard v-bind="args">
        <template v-if="$props.default" v-slot>
            <p>↓Content of slot displayed below</p>
            ${args.default}
        </template>
      </UICard>
    `,
  }),
  args: {
    ...Playground.args,
    // 将对象转为JSON字符串并转义单引号
    default: `<UIButton v-bind="JSON.parse('${JSON.stringify(disabledArgs).replace(/'/g, "\\'")}')" />`,
  },
}

方案一的可读性和维护性更好,不会因为参数结构复杂出现转义问题,更推荐使用。

内容的提问来源于stack exchange,提问作者user16589580

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 06:27:48