Fra*_*ost 5 javascript vue.js vue-router vuex vuex-modules
我有一个命名空间 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]
})
}
Run Code Online (Sandbox Code Playgroud)
这对于初始负载来说按预期工作。但是,每当路线发生变化时,它都不会重新加载。
有没有办法在路线改变时重新加载/强制重新计算吸气剂?
在路由器模块中导入商店会更受支持,反之亦然。您可以使用beforeEach
导航卫士来设置商店中的当前路线。首先,准备商店:
商店.js
state: {
route: null
},
mutations: {
SET_ROUTE(state, route) {
state.route = route;
}
},
modules: { ... }
Run Code Online (Sandbox Code Playgroud)
在router模块中,使用beforeEach
guard来存储当前的路由,即参数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();
});
Run Code Online (Sandbox Code Playgroud)
要在 Vuex 模块 getter 中访问此路由,请通过第三个 getter 参数访问它rootState
:
商店/someModule.js
getters: {
getRoute(state, getters, rootState) {
return rootState.route;
}
}
Run Code Online (Sandbox Code Playgroud)