Storybookを利用することで、プロジェクトで作成したコンポーネントのカタログを作ることができます。
どういうコンポーネントかも視覚的にわかりドキュメントとしていいものになると思います。
今回は、vue.jsでStorybookを利用してみます。
※他にもAnguler,Reactでも利用できますが利用方法については、Storybookガイドを参照してください。
前提
vue.jsプロジェクトについては、vue-cliを使ってvue.jsを使ったプロジェクトの開発環境を整えるの通りvue-cliを使用し、webpackテンプレートを使用して作成したものとします。
環境
項目 | バージョン |
---|---|
node | 9.11.1 |
vue-cli | 2.9.3 |
vue.js | 2.5.2 |
storybook | 3.4.6 |
Storybookを導入
StorybookのガイドのQuick Start Guideにある通りgetstorybook
を利用します。
1 2 |
npx -p @storybook/cli getstorybook |
getstorybook
が完了すると、以下にディレクトリが追加されています。
ディレクトリ | 説明 |
---|---|
.storybook | StorybookのConfigディレクトリ |
src/stories | 各storyディレクトリ |
getstorybook
で導入すると、index.stories.js
の記述が原因で起動時にエラーが発生します。
そのため、issues:2727に記載の通り以下の記述を削除する必要があります。
1 2 3 4 5 6 7 8 |
.add('with JSX', () => ({ components: { MyButton }, render() { return With JSX; }, methods: { action: linkTo('clicked') }, })) |
Storybook起動
起動にはnpm script
として追加されているstorybook
を利用します。
1 2 |
npm run storybook |
起動すると、http:localhost:6060
にアクセスしてみてください。
getstorybook
でsrc/stories
に作成されているstoryが表示されます。
これで、導入は完了です。
コンポーネントのstoryを作成
getstorybook
で作成されたsrc/stories
以下の各ファイルは不要なので削除し、.stories.js
で終わるファイルを作成します。
そして、storiesOf
の第1引数にストーリーグループ名を入力します。
続けて、add
関数で追加したいコンポーネントのstoryを記述します。
以下はSampleButton
コンポーネントのstoryを記述している例です。
Buttonグループにデフォルトの表示と、デフォルトサイズとFullサイズの違いを確認できるようにしました。
- index.stories.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import { storiesOf } from '@storybook/vue'; import { action } from '@storybook/addon-actions'; import SampleButton from '../components/SampleButton.vue'; storiesOf('Button', module) .add('default', () =&gt; ({ components: { SampleButton }, template: ` ` })) .add('Size', () =&gt; ({ components: { SampleButton }, template: ` <div> <div></div> <div></div> </div> `, methods: { action: action('clicked') } })); |
- SampleButton.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
<br /><button> {{ text }} </button> export default { name: "sample-button", props: { text: { type: String, default: "default" }, size: { type: String, default: null } }, computed: { classies() { return this.size ? ['button', this.size] : ['button'] } }, methods: { onClick() { console.log(this.size) this.$emit("click"); } } } .button { font-size: 16px; font-weight: bold; border: solid 1px; border-radius: 5px; margin: 5px; padding: 3px 5px; width: 120px; height: 40px; } .button:hover { opacity: 0.3; } .full { width: 100%; } |