• 熟悉Vue路由的beforeEach陷入死循环的情况


    Vue的全局路由分为全局前置路由与全局后置路由

    官方对前置路由守卫的介绍

    在这里插入图片描述
    不了解路由守卫的next很容易让页面陷入死循环。

    以全局前置路由为例,陷入路由死循环一般报错是堆栈溢出也就是:RangeError: Maximum call stack size exceeded

    router.js

    import Vue from 'vue'
    import VueRouter from 'vue-router'
    
    Vue.use(VueRouter)
    
    const routes = [
      {
        path:"/",
        redirect:"/Index"
      },
      {
        path:"/Index",
        component:()=>import('@/views/Index.vue')
      },
      {
        path:"/Center",
        component:()=>import('@/views/Center.vue')
      },
      {
        path:"/an",
        component:()=>import('@/views/an.vue')
      }
    ]
    
    const router = new VueRouter({
      routes
    })
    
    router.beforeEach((to,from,next)=>{
      console.log("to==>",to);
      console.log("from==>",from);
      if(from.path=='/Index'){
        next('/an')
      }else{
        next();
      }
    })
    
    export default router
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39

    当从Index.vue离开时就会陷入死循环。

    在这里插入图片描述
    要清楚前置路由陷入死循环的原因,就要明白前置路由守卫的next函数

    next函数与beforeEach前置守卫是互相调用的有个过程。
    next(‘/’)执行完成后就会执行beforeEach路由守卫

    router.beforeEach((to,from,next)=>{
      console.log("to==>",to.path);
      console.log("from==>",from.path);
      if(from.path=='/Index'){
        next('/an')
      }else{
        next();
      }
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    在这里插入图片描述
    流程解析:刚开始的时候 目标路由是/Center,来源路由是/Index,执行前置路由守卫,判断到if为true,于是执行next(‘/an’),目标路由改成了/an,但来源路由仍然是/Index,next执行完成后再次执行beforeEach,beforeEach的判断再次为true,再次执行next(‘/an’),目标路由改成/an,来源路由仍然没变,因为next执行完成后再次执行beforeEach,于是就陷入了死循环。


    如果要判断to.path陷入死循环,只需要to.path的值等于next的入参。
    router.beforeEach((to,from,next)=>{
      console.log("to==>",to.path);
      console.log("from==>",from.path);
      if(to.path=='/Index'){
        next('/Index')
      }else{
        next();
      }
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
  • 相关阅读:
    WordPress搭建
    CSS样式怎么实现圆角矩形功能
    使用 compose 的 Canvas 自定义绘制实现 LCD 显示数字效果
    在学习DNS的过程中给我的启发
    【Vue】深究计算和侦听属性的原理
    【Java面试】第三章:P6级面试
    使用Docker安装MySQL
    Python绘制X-bar图和R图 | 统计过程控制SPC
    TML+CSS+JS大作业:腾讯课堂首页 1页 侧拉菜单
    redis未授权访问漏洞
  • 原文地址:https://blog.csdn.net/qq_44849271/article/details/125565601