Vue.js - 获取 Vuex 模块中的当前路由

Vue.js - Get current route in Vuex module

我有一个命名空间的 vuex 商店,returns 商店的一个条目基于当前路由的参数。

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]
  })
}

对于初始加载,这按预期工作。但是,每当路由更改时,它都不会重新加载。

有没有办法在更改路线时重新加载/强制重新计算 getter?

在路由器模块中导入商店会更受支持,反之亦然。您可以使用 beforeEach 导航守卫来设置商店中的当前路线。一、准备店铺:

store.js

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

router模块中,使用beforeEach守卫存放当前路由,也就是to参数:

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();
});

要在 Vuex 模块 getter 中访问此路由,请通过第三个 getter 参数访问它,rootState:

store/someModule.js

getters: {
  getRoute(state, getters, rootState) {
    return rootState.route;
  }
}