如何从组件的动作动态改变 Storybook v6 中的“args”?

Ky6*_*6uk 12 javascript typescript vue.js storybook

让我们看看我们有一个简单的组件ToggleButton

const ButtonComponent = Vue.component('ButtonComponent', {
  props: {
    value: Boolean
  },

  methods: {
    handleClick() {
      this.$emit('toggle');
    }
  },

  template: `
    <button 
      :class="value ? 'on' : 'off'"
      @click="handleClick"
    >
      Toggle
    </button>`
});
Run Code Online (Sandbox Code Playgroud)

以及该组件的故事:

import ToggleButton from './ToggleButton.vue';

export default {
  title: 'ToggleButton',
  component: ToggleButton,

  argTypes: {
    onToggle: {
      action: 'toggle' // <-- instead of logging "toggle" I'd like to mutate `args.value` here
    }
  }
};

export const Default = (_args, { argTypes }) => ({
  components: { ToggleButton },
  props: Object.keys(argTypes),

  template: `
    <ToggleButton
      :value="value"
      :toggle="onToggle"
    />
  `
});

Default.args = {
  value: false
}
Run Code Online (Sandbox Code Playgroud)

我想实现的是处理toggle这个故事,将里面的动作value,我已经在使用Default.args对象通过更改类名称更改按钮样式.off.on

Pro*_*eek 31

我遇到了同样的问题,并持续寻找了好几天,直到我偶然发现了这篇 github 帖子: https ://github.com/storybookjs/storybook/issues/12006

目前在我的 React 中(我确信 vue 方法会类似),我执行以下操作:

import React from 'react';
import CheckboxGroupElement from '../CheckboxGroup';
import { STORYBOOK_CATEGORIES } from 'elements/storybook.categories';
import { useArgs } from '@storybook/preview-api';

export default {
  component: CheckboxGroupElement,
  title: 'Components/CheckboxGroup',
  argTypes: {
    onChange: {
      control: 'func',
      table: {
        category: STORYBOOK_CATEGORIES.EVENTS,
      },
    },
  },
  parameters: { actions: { argTypesRegex: '^on.*' } },
};

const Template = (args) => {
  const [_, updateArgs] = useArgs();

  const handle = (e, f) => {
// inside this function I am updating arguments, but you can call it anywhere according to your demand, the key solution here is using `useArgs()`
// As you see I am updating list of options with new state here
    console.log(e, f);
    updateArgs({ ...args, options: e });
  };
  return <CheckboxGroupElement {...args} onChange={handle} />;
};

export const CheckboxGroup = Template.bind({});
CheckboxGroup.storyName = 'CheckboxGroup';
CheckboxGroup.args = {
//Here you define default args for your story (initial ones)
  controller: { label: 'Group controller' },
  options: [
    { label: 'option 1', checked: true },
    { label: 'option 2', checked: false },
    { label: 'option 3', checked: false },
  ],
  mode: 'nested',
};
Run Code Online (Sandbox Code Playgroud)

  • 这通常是 Storybook 的方式,不是吗?您正在寻找文档中从未提及的功能,却在其源代码深处或 GitHub 问题中找到它。 (25认同)