4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

this.$route.nameをStorybookで使えるようにする方法

Last updated at Posted at 2019-10-21

背景

Nuxt.jsのthis.$route.nameを使ってページによって異なる処理を行うコンポーネントを作りました。

<template>
  <!-- 中略 -->
</template>

<script>
export default {
  name: 'Component',
  computed: {
    isHoge: function() {
      return this.$route.name === 'hoge'
    }
  }
}
</script>
import { storiesOf } from '@storybook/vue'
import { action } from '@storybook/addon-actions'
import StoryRouter from 'storybook-vue-router'

import Component from './Component.vue'

storiesOf('Components', module)
  .add('Component', () => ({
    components: { Component },
    template: '<component />'
  }))

これをStorybookで表示&動作確認したかったのですが、

Cannot read property 'name' of undefined

となって表示できませんでした。
解決法を調べましたので備忘録として残します。

解決法

https://github.com/gvaldambrini/storybook-router を使うことにしました。
Nuxt.jsなので https://github.com/gvaldambrini/storybook-router/tree/master/packages/vue に倣いインストールします。

npm install --save-dev storybook-vue-router
import { storiesOf } from '@storybook/vue'
import { action } from '@storybook/addon-actions'
import StoryRouter from 'storybook-vue-router'

import Component from './Component.vue'

storiesOf('Components', module)
  .addDecorator(StoryRouter({}, { initialEntry: { name: 'hoge' } })) //<--追記
  .add('Component', () => ({
    components: { Component },
    template: '<component />'
  }))

これで期待通り動きました。

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?