vue.js:路由保护等待异步值

san*_*oco 1 state vue.js vue-router vuex

就像在每个应用程序中一样,我有几条路线。例如(router/index.js摘录):

[{
    path: '/reporting',
    name: 'Reporting',
    component: reporting,
    meta: {
        adminOnly: true
    }
},
...]
Run Code Online (Sandbox Code Playgroud)

正如您在路由定义中看到的,访问时reporting用户需要具有管理员权限,这是 vuex 存储中的一个属性。问题:这个属性是异步的,并且在最初访问守卫时当然是错误的。我怎样才能让我的守卫等待呢?

警卫:

if (to.matched.some(route => route.meta.adminOnly)) {
    if (store.getters.userInfo.isAdmin) {
        next()
    } else {
      next('/')
    }
} else {
    next()
}
Run Code Online (Sandbox Code Playgroud)

Cob*_*way 5

使用store.watch来观察 getter 怎么样?

null假设如果尚未获取数据,则getter 返回。

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('/');
Run Code Online (Sandbox Code Playgroud)