Vue-Router, 路由独享的守卫的使用 beforeRouteLeave

一些需求都可以通过阅读文档来解决,简单说下 组件内守卫 使用时
next() 方法使用的问题

官方文档 https://router.vuejs.org/zh/guide/advanced/navigation-guards.html#全局后置钩子

beforeRouteLeave

Vue-Router, 路由独享的守卫的使用 beforeRouteLeave

a 页面  b 页面
当从a页面 进入 b页面时,
b页面做了一些操作, 在b页面判断离开时,
//使用组件内守卫,对离开页面事件做一些操作,
beforeRouteLeave(to, from, next){
	if(from.path=='/b'){ //当前页面路由
				next({replace: true,redirect: '/a'}); //目标路由 重定向
			}else {
		next()
	}
}

为什么不直接用 next(’/a’)

从打印出的 to.path 可以看到 当前路由离开进入的下一个路由 已经 是 【/a】
如果这时我们 用next('/a') 则会陷入 栈溢出 无限循环的尴尬,

所以采用next({replace: true,redirect: '/a'}); // 对目标路由进行重定向的方式在跳转到目标路由

当然 如果要跳转的路由不是 to.path 中的 path 路径 是可以直接 使用next(‘/n’)的
在 使用beforeRouteLeave(to, from, next){} 时 你必须要做一些判断。 来调用next()