我有一个命名空间的 vuex 存储,它根据当前路由的参数返回存储的条目。
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]
})
}
这对初始负载按预期工作。但是,只要路由更改,它就不会重新加载。有没有办法重新加载/强制在更改路线时重新计算 setter/getter ?
最佳答案
在路由器模块中导入商店会更受支持,反之亦然。您可以使用 beforeEach
导航守卫设置商店中的当前路线。首先,准备商店:
store.js
state: {
route: null
},
mutations: {
SET_ROUTE(state, route) {
state.route = route;
}
},
modules: { ... }
在路由器模块中,使用 beforeEach
守卫存储当前路线,即to
争论:路由器.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
访问它:商店/someModule.js
getters: {
getRoute(state, getters, rootState) {
return rootState.route;
}
}
关于javascript - Vue.js - 在 Vuex 模块中获取当前路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65995093/