Skip to content
Advertisement

Vue.js – Get current route in Vuex module

I have a namespaced vuex store that returns an entry of the store based on the parameter of the current route.

import Router from '../../router/index'

const options = {
  routeIdentifier: 'stepId'
}

export function fromRoute(state) {
  if (!options.routeIdentifier || !Router.currentRoute.params) {
    return null
  }

  return state.all.find(element => {
    return element.identifier === Router.currentRoute.params[options.routeIdentifier]
  })
}

This works as expected for the initial load. However, it is not reloaded whenever the route changes.

Is there a way to reload / force the recalculation of the getter on change of the route?

Advertisement

Answer

It would be more supported to import the store in the router module rather than vice versa. You can use the beforeEach navigation guard to set the current route in the store. First, prepare the store:

store.js

state: {
  route: null
},
mutations: {
  SET_ROUTE(state, route) {
    state.route = route;
  }
},
modules: { ... }

In the router module, use the beforeEach guard to store the current route, which is the to argument:

router.js

import store from '@/store';  // Import the store in the router module

const router = new VueRouter({
  ...
})

router.beforeEach((to, from, next) => {
  store.commit('SET_ROUTE', to);
  next();
});

To access this route in a Vuex module getter, access it through the third getter argument, rootState:

store/someModule.js

getters: {
  getRoute(state, getters, rootState) {
    return rootState.route;
  }
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement