vue路由守卫

时间:2020-04-14
本文章向大家介绍vue路由守卫,主要包括vue路由守卫使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

当用户未登录,进入首页地址,会强制转向登录页。只有登录的用户才可以进入首页。

//路由守卫---路由一旦改变,就会触发
//to  -- 即将进入的页面(下一个页面)
//from --即将离开的页面(上一个页面)
router.beforeEach((to, from, next) => {
    console.log(to,from,next)
})

错误写法:

router.beforeEach((to, from, next) => {
	if (TOKEN) {
		next()
	} else {
		next("/login") 
                //会陷入死循环
		/*next('/login')   括号里有参数,就会重新触发router.beforeEach() ,一直进入死循环*/
		/*next()  默认放行到to指向的path。括号里没有参数,不会触发router.beforeEach*/
	}
})

正确写法:

//路由白名单
const whiteRouter = ["/login"]

router.beforeEach((to, from, next) => {
	if (getToken()) {
	} else {
	    if (whiteRouter.indexOf(to.path) !== -1) {
		//在白名单里
		next()
	    } else {
		//没有在白名单里
		next("/login")
	    }
	}

原文地址:https://www.cnblogs.com/maizilili/p/12698312.html