首页 > 解决方案 > Vue Router Navigation Guard 动态导入

问题描述

我想将组件文件中的数据动态导入路由器文件根据导入数据的值允许。next()

App.vue中,this.$router.push({name: "Dashboard"})数据 authenticated: false更改为true. 我用 触发它watch

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


应用程序.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方法,但没有任何效果。

标签: javascriptvue.jsvuejs2vue-componentvue-router

解决方案


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

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

推荐阅读