VueRouter beforeEach方法中如何避免死循环问题?
- 内容介绍
- 文章标签
- 相关推荐
本文共计225个文字,预计阅读时间需要1分钟。
javascriptrouter.beforeEach((to, from, next)=> { const isLogin=sessionStorage.getItem('loginData'); if (isLogin) { next(); } else { next('/error'); }});
router.beforeEach((to,from,next)={constisLogin=sessionStorage.getItem(loginData)router.beforeEach((to, from, next) = { const isLogin = sessionStorage.getItem('loginData') if (isLogin) { next() } else { next('/error') }})
最近在使用时,一直陷入死循环,当时的想法是如何将路由提取出来,脱离beforeEach的控制,之后发现不可行。上面问题再现,会出现死循环,因为 /error 会在进入前 又要进入beforeEach中 ,这样就会一直循环下去
所以就是想如何跳出这个循环即可
router.beforeEach((to, from, next) = { const isLogin = sessionStorage.getItem('loginData') if (isLogin) { next() } else { //next('/error') if (to.path === '/error') { //这就是跳出循环的关键 next() } else { next('/error') } }})
这样写,其实这个会执行两次,第二次进来是以/error的路由进来的
总结
看文档也需要 实践哈
本文共计225个文字,预计阅读时间需要1分钟。
javascriptrouter.beforeEach((to, from, next)=> { const isLogin=sessionStorage.getItem('loginData'); if (isLogin) { next(); } else { next('/error'); }});
router.beforeEach((to,from,next)={constisLogin=sessionStorage.getItem(loginData)router.beforeEach((to, from, next) = { const isLogin = sessionStorage.getItem('loginData') if (isLogin) { next() } else { next('/error') }})
最近在使用时,一直陷入死循环,当时的想法是如何将路由提取出来,脱离beforeEach的控制,之后发现不可行。上面问题再现,会出现死循环,因为 /error 会在进入前 又要进入beforeEach中 ,这样就会一直循环下去
所以就是想如何跳出这个循环即可
router.beforeEach((to, from, next) = { const isLogin = sessionStorage.getItem('loginData') if (isLogin) { next() } else { //next('/error') if (to.path === '/error') { //这就是跳出循环的关键 next() } else { next('/error') } }})
这样写,其实这个会执行两次,第二次进来是以/error的路由进来的
总结
看文档也需要 实践哈

