Problem displaying components that use $route with vue-styleguidist

326 Views Asked by At

I have some components that use this.$route internally, for various things. Some simplified examples would be, using this.$route.name to lookup a i18n string for the page:

<h1>New {{ $t($route.name + '.label') }}</h1>

or watching the $route and loading something:

watch: {
    $route: {
      handler: 'loadItem',
      immediate: true
    }
  }

Whenever these components appear in vue-styleguidist, I get various errors in the browser console and nothing renders for the component example:

index.js?1ef8:1 [Vue warn]: Error in callback for immediate watcher "$route": "TypeError: Cannot read property 'id' of undefined"

found in

---> <MyComponent> at src/components/MyComponent.vue
       <Anonymous>
         <Root>

I am deliberately not importing vue-router or my routes objects into the styleguide, because this isn't supported - and it causes lots of problems with redirects, route guards, etc... which aren't relevant to the style guide.

What I really want to do, I think, is to mock this.$route inside the components when they appear in the styleguide - but I can't figure out how to do that.

Another option would be to pass the route information into the components as props. This would properly decouple the components from the router and fix the issue, but it will involve changes to every component and route.

1

There are 1 best solutions below

0
On

So, I ended up refactoring all my components to pass in the route properties that they were using as properties. This properly decouple the components from the router and fix the issue, but it was a lot of work.