iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 7
1
Modern Web

玩轉 Storybook系列 第 7

玩轉 Storybook: Day 07 Write stories

  • 分享至 

  • twitterImage
  •  

Template & Args

同一個元件的多個story function,都會重複的指定相同的Template,可以拉出一個共用 template function,讓template能在多個stories之間共用。元件的props使用args這個變數名,傳入template function。

// Vue 的 Story Template 寫法
const Template = (args) => ({
  props: Object.keys(args),
  components: { MyButton },
  template: '<my-button @onClick="onClick" v-bind="$props" />',
});
// Angular 的 Story Template 寫法
const Template: Story<Button> = (args: Button) => ({
  component: Button,
  props: args,
});

每個Story使用Template.bind({})語法跟Template做綁定。Story就擁有了Template,透過修改NamedStory.args,就可以改變元件的樣式,達到描述元件不同的狀態。

// Vue 及 Angular 的寫法在此是一樣
export const Primary = Template.bind({});
Primary.args = {
  primary: true,
  label: 'Button',
};

export const Secondary = Template.bind({});
Secondary.args = {
  label: 'Button',
};

export const Large = Template.bind({});
Large.args = {
  size: 'large',
  label: 'Button',
};

export const Small = Template.bind({});
Small.args = {
  size: 'small',
  label: 'Button',
};

試看看

修改Button程式碼,加上可以指定顯示outline的功能

然後在Stories把Outline的狀態顯示出來

Vue

完整程式碼:https://git.io/JUBvg

  • src/stories/button.css
.storybook-button--outline {
  border-width: 1px;
  border-style: solid;
}
  • src/stories/Button.vue
props: {
  outline: {
    type: Boolean,
    default: false,
  },
  outlineColor: {
    type: String,
  },
}
computed: {
  classes() {
    return {
     ...
     'storybook-button--outline': this.outline,
    };
  },
  style() {
    return {
      ...
      borderColor: this.outlineColor,
    };
  },
},
  • src/stories/Button.stories.js
export const BlackOutline = Template.bind({});
BlackOutline.args = {
  label: 'Black Outline Button',
  outline: true,
  outlineColor: 'black',
};

export const GreenOutline = Template.bind({});
GreenOutline.args = {
  label: 'Green Outline Button',
  outline: true,
  outlineColor: 'green',
};

Angular

完整程式碼:https://git.io/JU4az

  • src/stories/button.css
.storybook-button--outline {
  border-width: 1px;
  border-style: solid;
}
  • src/stories/button.component.ts

    修改的程式碼片段如下圖所示

  • src/stories/Button.stories.ts

export const BlackOutline = Template.bind({});
BlackOutline.args = {
  label: 'Black Outline Button',
  outline: true,
  outlineColor: 'black',
};

export const GreenOutline = Template.bind({});
GreenOutline.args = {
  label: 'Green Outline Button',
  outline: true,
  outlineColor: 'green',
};

執行結果

執行 npm run storybook,可以看到顯示結果

補充

在官方產生的檔案,有一個ArgTypes的設定,這個argTypes會在後面產出Doc的單元會介紹,先看看就好。

Next

接下來會介紹Parameters及Decorators,用來更完善Story的撰寫。

Reference

官方CSF的說明:VueAngular

Writing Stories:VueAngular


上一篇
玩轉 Storybook: Day 06 Component Story Format
下一篇
玩轉 Storybook: Day 08 Parameters
系列文
玩轉 Storybook30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言