【发布时间】:2021-05-01 18:59:05
【问题描述】:
我一直在努力使用vuex.getters,它是从vuex.actions 计算出来的,作为router.beforeEach 中的if 语句。
这是我想要做的:
-
每次用户进入网站时获取一组对象。
-
然后使用
array.find()根据router.params.id定位具有相同slug的一个对象,以防用户通过直接url进入站点。 -
如果
router.params.id与对象数组中的任何 slug 都不匹配,则将路由重定向到 404。
这是我的方法
const router = new VueRouter(
{
routes: [
{
path: '/list/:id',
name: 'list'
},
{
path: '/edit/:id',
name: 'edit'
},
//other routes
{
path: '/*',
name: '404'
}
]
}
);
router.beforeEach((to, from, next)=>{
if ( !store.state.lists.length ){
// fetch Object Array when user first enter
store.dispatch('fetchLists');
}
if ( to.name === 'list' || to.name === 'edit'){
// limit route only 'list' & 'edit', preventing passing undefined params
store.commit('cloneParams', to);
// determine if currentMonth has a valid slug, if not go to 404
store.getters.currentMonth.slug !== '' ? next() : next('/404');
} else {
next();
}
});
getters: {
currentMonth(state){
var template = {
month: '',
slug: '',
data: []
}
var obj = template;
if ( state.lists.length ) {
obj = state.lists.find(current => current.slug === state.paramsID);
if ( obj === undefined ){
obj = template
}
}
return obj;
},
actions: {
fetchLists({commit}){
axios('/lists').then(
res=>{
commit('storeList', res);
}
)
},
mutations: {
storeList(state, res){
state.lists = res.data;
},
cloneParams(state, to){
state.paramsID = to.params.id;
},
但是,我发现在获取对象数组 store.state.lists 并转到 404 后,getter currentMonth 不会更新。同时,当用户转到下一个其他对象时,在获取并存储 store.state.lists 后它工作得很好此 SPA 的页面。
【问题讨论】:
标签: javascript vue.js vuex vue-router es6-promise