what is vuex-router-sync for?

Viewed 16959

As far as I know vuex-router-sync is just for synchronizing the route with the vuex store and the developer can access the route as follows:

store.state.route.path
store.state.route.params

However, I can also handle route by this.$route which is more concise.

When do I need to use the route in the store, and what is the scenario in which I need vuex-router-sync?

2 Answers

I saw this thread when I was learning Vue. Added some of my understanding on the question.

Vuex defines a state management pattern for Vue applications. Instead of defining component props and passing the shared state through props in all the places, we use a centralized store to organize the state shared by multiple components. The restriction on state mutation makes the state transition clearer and easier to reason about.

Ideally, we should get / build consistent (or identical) views if the provided store states are the same. However, the router, shared by multiple components, breaks this. If we need to reason about why the page is rendered like it is, we need to check the store state as well as the router state if we derive the view from the this.$router properties.

vuex-router-sync is a helper to sync the router state to the centralized state store. Now all the views can be built from the state store and we don't need to check this.$router.

Note that the route state is immutable, and we should "change" its state via the $router.push or $router.go call. It may be helpful to define some actions on store as:

// import your router definition
import router from './router'

export default new Vuex.Store({
  //...
  actions: {
    //...
    // actions to update route asynchronously
    routerPush (_, arg) {
      router.push(arg)
    },
    routerGo (_, arg) {
      router.go(arg)
    }
  }
})

This wraps the route updates in the store actions and we can completely get rid of the this.$router dependencies in the components.

Related