zoukankan      html  css  js  c++  java
  • 关于vue-router的beforeEach无限循环的问题

    最近在使用vue-router的beforeEach钩子时候遇到了一个问题,就是在beforeEach()中设置好判断条件后出现了无限循环的问题
    代码如下:

    // isLogined 用来判断用户是否已登录
    router.beforeEach((to, from, next) => {
      if(isLogined){
        next()
      }else{
        console.log('测试')
        next('login')
      }
    })

    结果chrome的debug中看到:

    clipboard.png

    这个问题我是这样理解的:

    router.beforeEach((to, from, next) => {
        if(true){
            next()
        }else{
            next('login')
        }
    })
    • next() 表示路由成功,直接进入to路由,不会再次调用router.beforeEach()
    • next('login') 表示路由拦截成功,重定向至login,会再次调用router.beforeEach()

    也就是说beforeEach()必须调用next(),否则就会出现无限循环,
    next() 和 next('xxx') 是不一样的,区别就是前者不会再次调用router.beforeEach(),后者会!!!

    官网这样写的(主要是红线标记的那句!):

    clipboard.png

      

    就上面的例子,next('login') 和 判断条件isLogin 就是一个无限死循环,只需要给 login 路由放行就可以解决问题了,在开始加一条判断if (to.name === 'login' && !isLogin){next()},这样就可以解决问题了。

    原文链接:https://segmentfault.com/a/1190000011042794

  • 相关阅读:
    一步一步本地化部署mapbox-gl
    快速排序
    合并排序
    冒泡排序
    选择排序
    插入排序
    mapbox-gl象形文字字体glyph生成
    前端html
    Mysql练习
    Mysql语句
  • 原文地址:https://www.cnblogs.com/momo798/p/14958844.html
Copyright © 2011-2022 走看看