How to use VueRouter with Storybook

Viewed 32

I'm trying to write a story for a component that references this.$route.params. I'm not sure how to synthetically define this.$route in the context of a story. I think the solution is to use decorators, but all the examples in the docs focus on rendering, like adding a wrapping <div> etc. I'm not sure how to inject values.

I also found this project which appears designed for this exact situation, but it hasn't been maintained in years and README references outdated syntax that doesn't match modern versions of Storybook, so I don't think it's an option.

Here's what doesn't work:

import AssetShow from '../app/javascript/src/site/components/assets/Show'
    
export default {
  title: 'Site/AssetShow',
  component: AssetShow,
  parameters: {
  }
};

export const CustomerSpotlight = () => ({
  components: { AssetShow },
  template: '<AssetShow />',
});
import Vue from 'vue'
import VueRouter from 'vue-router'
import StoryRouter from 'storybook-vue-router';

CustomerSpotlight.decorators = [

  (story) => { 

    Vue.use(VueRouter)

    return {
      components: { story },
      template: '<story />'
    }
  }
];

The component I'm writing the story for has this:

mounted() {
 axios.get(`.../bla/${this.$route.params.id}.json`)
},

...which causes Storybook to throw this error: TypeError: Cannot read properties of undefined (reading 'params')

1 Answers

I suppose that your intention is to do something with the story's component based on the route parameters?

If that is the case, then I don't think you need to define the route.params within the story context. I suggest either keeping that code within the component itself, or create an option within the story for the user to simulate adding parameters to the path. Which you can simply have as an input text / select field that you send down to the component as a prop.

Related