【问题标题】:vue.js: Route guard wait for async valuevue.js:路由守卫等待异步值
【发布时间】:2018-01-10 18:43:57
【问题描述】:

在每个应用程序中,我都有一些路线。例如(router/index.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()
}

【问题讨论】:

  • 您如何以及在何处获取此属性?
  • 在 vuex 存储中 init 完成。
  • 那么您不应该在该登录操作解决之前启动您的应用程序。当行动返回一个承诺时,你应该很容易。

标签: vue.js state vue-router vuex


【解决方案1】:

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

假设您的 getter 在尚未获取数据的情况下返回 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('/');

【讨论】:

  • 它抛出[vuex] store.watch only accepts a function...?
  • 好吧,我想通了:你的 getter 返回一个实际的函数很重要,getter 本身是不够的。 someGetter(state) { return function () { return state.xx } }
  • 是否有避免重复代码if store.getters.userInfo.isAdmin) next(); else next('/'); 的模式?你会怎么做?
  • @sandrooco 你能在这里回答你是如何解决这个错误的吗:它抛出 [vuex] store.watch 只接受一个函数stackoverflow.com/questions/64511941/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-22
  • 2018-07-09
  • 1970-01-01
  • 2019-11-11
  • 2019-02-04
  • 2018-12-04
  • 2017-11-11
相关资源
最近更新 更多