Accessing Vuex state when defining Vue-Router routes

后端 未结 6 1949
野的像风
野的像风 2020-11-27 15:53

I have the following Vuex store (main.js):

import Vue from \'vue\'
import Vuex from \'vuex\'

Vue.use(Vuex)

//init sto         


        
6条回答
  •  孤独总比滥情好
    2020-11-27 16:04

    Importing the store as @Saurabh suggested works. However IMHO it brings a certain workaround smell into your code.

    It works, because the Vuex store is a singleton. Importing it it creates a hard linked dependency between your component, the routers and the store. At the very least it makes it harder to unit test. There is a reason why vue-router is decoupled and works like this and it may pay off to follow its suggested pattern and to keep the router decoupled from the actual store instance.

    Looking at the source of vue-router it becomes apparent that there is a more elegant way to access the store from the router, e.g. in the beforeRouteEnter guard:

    beforeRouteEnter: (to, from, next) => {
      next(vm => {
        // access any getter/action here via vm.$store
        // avoid importing the store singleton and thus creating hard dependencies
      })
    }
    

    Edit on 10. Sept 2020 (thanks @Andi for pointing that out)

    Using the beforeRouteEnter guard is then up to the concrete case. Off the bat I see the following options:

    1. Declare the guard in a mixin and selectively use it in the components that need it, instead of filtering needed components in a global guard
    2. Declare the guard in a global mixin (beware of declaration peculiarities, e.g. needs to be declared after Vue.use(VueRouter);: here and here)

提交回复
热议问题