本文主要是介绍熟悉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();}
})
这篇关于熟悉Vue路由的beforeEach陷入死循环的情况的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!