【问题标题】:Vue Router Navigation Guard Dynamic ImportVue Router Navigation Guard 动态导入
【发布时间】:2020-12-09 05:56:15
【问题描述】:

我想将 datacomponent 文件 动态导入 router 文件 并根据导入 data 的值允许 next() .

App.vue 中,当 data authenticated: false 更改为 true 时,我正在触发 this.$router.push({name: "Dashboard"})。我用watch 触发它。

问题是,路由器文件总是会收到原始值false,即使是动态导入。


App.vue

watch: {
      authenticated(){
         console.log(this.authenticated)             //Outputs 'true'
         this.$router.push({name: 'Dashboard'});     //Triggers routing
      }
   }

路由器文件 (index.js)

{
      path: '/dashboard',
      name: 'Dashboard',
      component: Dashboard,
      beforeEnter(to, from, next){
         (async ()=>{
            const mod = await import('../view/App.vue');  //Dynamic import
            let result = mod.default.data().auth;         //Access 'authenticated' value from App.vue
            console.log(result);                          //Output is 'false', but it should be 'true'
            result ? next() : next({name: 'Login'});
         })()
      }
}

我也尝试了许多不同的async 方法,但没有任何效果。

【问题讨论】:

  • 您访问的是auth 而不是authenticated

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


【解决方案1】:

App.vue 中使用In-Component Guard 指定here 并从router 文件中删除身份验证登录:

beforeRouteLeave(to, from, next) {
    if (to.name === 'Dashboard' && this.authenticated) {
        next();
    }
    else {
        next({ name: 'Login' });
    }
}

【讨论】:

  • 此答案基于您提出的问题范围。根据项目结构,身份验证逻辑可能会变得非常多样化。我建议将authenticated 变量存储在vuex 中,以便每个需要身份验证的组件都可以访问该变量
  • 感谢您的回答。我在App.vue 中声明了beforeRouteEnter(from, to, next),但它没有触发。 App.vue 是仪表板的 <router-link> 所在的位置。我这样做对吗?
  • 只需将authenticated 变量存储在vuex 中,因为您也可以在其他地方使用此变量来保护不同的路由。然后您可以在beforeEnter 中使用authenticated 变量,正如您在问题中提到的那样:store.state.authenticated。见this
  • 我还没有学习 Vuex,但我想我必须坚持这个问题,直到我学会它。谢谢你的回答。
猜你喜欢
  • 2022-06-15
  • 2021-04-06
  • 2021-04-21
  • 2019-12-26
  • 2021-10-23
  • 2021-03-19
  • 2020-03-28
  • 2022-12-17
  • 2019-04-23
相关资源
最近更新 更多