Vue routing guard--for front-end user authorization verification

1. Usage scenarios

1.首次登录的时,前端调后端的登录接口,发送输入框中的用户名和密码;
2.后端收到请求,验证用户名和密码,验证成功,就给前端返回一个token(令牌相当于一个门牌,如返回对象);
3.前端拿到token,将token存储到localStorage和vuex中,并跳转路由页面
4.前端每次跳转路由,就判断 localStroage 中有无 token ,没有就跳转到登录页面,有则跳转到对应路由页面
5.每次调后端接口,都要在请求头中加token
6后端判断请求头中有无token,有token,就拿到token并验证token,验证成功就返回数据,验证失败(例如:token过期)就返回401,请求头中没有token也返回401
7.如果前端拿到状态码为401,就清除token信息并跳转到登录页面(首页)

2. The role of routing guards

对路由进行权限控制,用来判断用户是否登录,该页面用户是否有权限浏览,需要结合meta来实现

3. Classification of routing guards

全局守卫、独享守卫、组件内守卫

1. Global routing guard

Global front guard: Execute at initialization, before each routing switch
router.beforeEach((to,from,next)=>{})
回调函数中的参数,to:进入到哪个路由去,from:从哪个路由离开,next:函数,决定是否展示放行你要看到的路由页面。
router.beforeEach((to,from,next)=>{
    
    
	console.log('beforeEach',to,from)
	if(to.meta.isAuth){
    
     //判断当前路由是否需要进行权限控制
		if(localStorage.getItem('school') === 'yangcun'){
    
     //权限控制的具体规则
			next() //放行
		}else{
    
    
			alert('暂无权限查看')
			// next({name:'guanyu'})
		}
	}else{
    
    
		next() //放行
	}
})
Global post guard: Execute at initialization, after each routing switch
全局后置钩子router.afterEach((to,from)=>{})
只有两个参数,to:进入到哪个路由去,from:从哪个路由离开。
router.afterEach((to,from)=>{
    
    
	console.log('afterEach',to,from)
	if(to.meta.title){
    
     
		document.title = to.meta.title //修改网页的title
	}else{
    
    
		document.title = 'vue_test'
	}
})

2. Exclusive route guard

beforeEnter:(to,from,next)=>{},用法与全局守卫一致。只是,将其写进其中一个路由对象中,只在这个路由下起作用。
beforeEnter(to,from,next){
    
    
	console.log('beforeEnter',to,from)
	if(to.meta.isAuth){
    
     //判断当前路由是否需要进行权限控制
		if(localStorage.getItem('school') === 'yangcun'){
    
    
			next()
		}else{
    
    
			alert('暂无权限查看')
			// next({name:'guanyu'})
		}
	}else{
    
    
		next()
	}
}

3. Routing guards in components

到达当前守卫的组件时:
//进入守卫:通过路由规则,进入该组件时被调用beforeRouteEnter (to, from, next) {},
//离开守卫:通过路由规则,离开该组件时被调用beforeRouteLeave (to, from, next) {}
		// 通过路由规则,进入该组件时被调用
		beforeRouteEnter(to,from,next){
    
    
			console.log('About--beforeRouteEnter',to,from)
			if(to.meta.isAuth){
    
    
				if(localStorage.getItem('school')==='yangcun'){
    
    
					next()
				}else{
    
    
					alert('暂无权限查看')
				}
			}else{
    
    
				next()
			}
		},

		// 通过路由规则,离开该组件时被调用
		befortRouteLeave(to,from,next){
    
    
			console.log('About--beforeRouteEnte',to,from)
			next()
		}
	}

Guess you like

Origin blog.csdn.net/m0_66504310/article/details/128458971