【问题标题】:Vue: Using Vuex store in beforeRouteEnter hook to cancel navigationVue:在 beforeRouteEnter 钩子中使用 Vuex 存储取消导航
【发布时间】:2021-05-31 00:46:23
【问题描述】:

我正在尝试让 vue-router 在完成导航到新路线之前检查权限列表。权限存储在 vuex 中,理想情况下我希望避免将它们作为道具传递到任何地方。

当我使用next(vm => {}) 回调时,无论结果如何,它都会路由到下一页,即使它应该收到false 并取消导航。

beforeRouteEnter(to, undefined, next) {
  next(vm => {
    const allowedRoles = ['Administrator', 'Contributor'];
    if (vm.$store.state.authentication.userInfo.userRoles.some(value => allowedRoles.includes(value))) {
      return true;
    }
    else {
      return false;
    }
  });
}

我在这里做错了什么导致它失败?

【问题讨论】:

    标签: javascript vue.js vue-component vuex vue-router


    【解决方案1】:

    当您在next 中访问vm 时,导航已经开始。在调用next 之前测试该值。您可以将 store 导入到组件中进行访问:

    import store from '@/store/index.js';  // import the store
    
    beforeRouteEnter(to, undefined, next) {
      const allowedRoles = ['Administrator', 'Contributor'];
      const roles = store.state.authentication.userInfo.userRoles;
      const isAllowed = roles.some(value => allowedRoles.includes(value))
      next(isAllowed);  // passes `true` or `false` to `next`
    },
    

    这样你就可以在不需要组件实例的情况下访问商店。

    【讨论】:

    • 不幸的是,我们不使用像 webpack 这样的打包工具,而是通过类似 CDN 的方法来做事。如果我们试图在 vue 之外访问 Vuex,我们将不得不手动筛选 Vuex 实例的浏览器记录。我认为模块捆绑器是解决这个问题的唯一真正方法?
    • 商店对于应用程序来说是如此不可或缺,因此使其可以从任何地方访问(即使使用 CDN 时)都至关重要。如有必要,我会将其添加到 window 对象中。还有其他可能性。可以访问路由器中的商店吗?
    • 是的,分配给窗口得到了它。虽然我们避免直接写入窗口,所以我们把它放在一个嵌套类中,例如Page.Vuex = new Vuex.Store({});这意味着我们可以通过 Page.Vuex.state 在路由器中引用...
    猜你喜欢
    • 2020-11-17
    • 2019-07-01
    • 2018-08-07
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    • 2019-09-06
    • 2021-03-24
    • 2021-08-14
    相关资源
    最近更新 更多