熟悉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

当从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();
  }
})

在这里插入图片描述
流程解析:刚开始的时候 目标路由是/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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值