2017-08-03 80 views
0

正如每个应用程序中我有几条路线。例如(router/index.js节选):vue.js:路由守卫等待异步值

[{ 
    path: '/reporting', 
    name: 'Reporting', 
    component: reporting, 
    meta: { 
     adminOnly: true 
    } 
}, 
...] 

正如你可以在路线定义见,访问reporting当用户需要有管理员权限,这在vuex商店的属性。问题:这个属性是异步的,当初访问警卫时当然是错误的。我怎样才能让我的警卫等待呢?

后卫:

if (to.matched.some(route => route.meta.adminOnly)) { 
    if (store.getters.userInfo.isAdmin) { 
     next() 
    } else { 
     next('/') 
    } 
} else { 
    next() 
} 
+0

如何以及在哪里获取此属性? – Cobaltway

+0

它在init的vuex存储中完成。 – sandrooco

+0

然后在该登录操作解决之前,您不应该启动您的应用程序。随着行动回复承诺,你应该很容易。 –

回答

1

什么看,吸气,用store.watch

假设您的获得者返回null如果尚未获取数据。

if (store.getters.userInfo.isAdmin === null) { 
    const watcher = store.watch(store.getters.userInfo.isAdmin, isAdmin => { 
     watcher(); // stop watching 
     if (isAdmin) next(); 
     else next('/'); 
    }); 
} 
else if (store.getters.userInfo.isAdmin) next(); 
else next('/'); 
+0

它抛出'[vuex] store.watch只接受函数'...? – sandrooco

+0

好吧,我设法弄明白:重要的是你的getter返回一个实际的功能,getter本身是不够的。 'someGetter(状态){ 回报函数(){ 返回state.xx } }' – sandrooco

+0

有避免重复码'''如果store.getters.userInfo.isAdmin)next()的一个图案; else next('/');'''?你会怎么做? –