代码之家  ›  专栏  ›  技术社区  ›  Sergio

在地址栏中键入时,Vue路由器保护程序不会阻止受保护的路由

  •  0
  • Sergio  · 技术社区  · 6 年前

    它正在航行。。。因此,如果我没有登录,并点击“仪表板”,我会被重定向到会员登录页面。如果我登录并点击“登录”,我会被重定向到仪表板页面。很酷。

    除非我在地址栏中键入路径,也就是说,如果我登录并单击“登录”,我会被重定向到仪表板,但是如果我在地址栏中键入/成员登录,它仍然会将我带到成员登录页,而且不应该。如果我没有登录,则与仪表板页相反。

    我用的是 beforeEach()

    router.beforeEach((to, from, next) => {
       let ls = JSON.parse(localStorage.getItem('loggedInMember'));
       if(ls === null && to.name === 'dashboard'){ 
          next('/member-login');
       } else if ( ls !== null && to.name === 'login') { 
          next('/dashboard');
       } else {
          next();
       }
    });
    

    我应该提到,这是一个全局守护程序,它位于我的项目的main.js文件中。

    非常感谢!

    2 回复  |  直到 6 年前
        1
  •  1
  •   Sergio    6 年前

    所以,这个问题对我来说是个愚蠢的错误。。。

    router.beforeEach 方法低于 new Vue({}) 方法和它不喜欢那样。所以移动 beforeEach 方法高于 new Vue

    婴儿车:

    new Vue({
       el: '#app',
       router,
       store,
       components: { App },
       template: '<App/>'
    });
    
    router.beforeEach((to, from, next) => {
       let ls = JSON.parse(localStorage.getItem('loggedInMember'));
    
       if(ls === null && to.name === 'dashboard'){
          next('/member-login');
       } else if ( ls !== null && to.name === 'login') {
          next('/dashboard');
       } else {
          next();
       }
    });
    

    router.beforeEach((to, from, next) => {
       let ls = JSON.parse(localStorage.getItem('loggedInMember'));
    
       if(ls === null && to.name === 'dashboard'){
          next('/member-login');
       } else if ( ls !== null && to.name === 'login') {
          next('/dashboard');
       } else {
          next();
       }
    });
    
    /* eslint-disable no-new */
    new Vue({
       el: '#app',
       router,
       store,
       components: { App },
       template: '<App/>'
    });
    
        2
  •  0
  •   Jerry    6 年前

    你是说你输入了 /member-login 它会把你带到登录页面?在我看来,这是正确的行动,还是有一些误解? 你能提供更多细节吗?