导航守卫(处理一些跳转权限上的问题)

官网

直接粘贴复制

//导航守卫
router.beforeEach((to, from, next) => {
  // ...
})

三个参数

1,to跳转到那里去
2,from从哪里来
3,next这是一个放行的函数页面中必须得有

// 可以打印一下to可以得到一下的东西,我们需要的是path这个函数;
// console.log(to)
// fullPath: “/”
// hash: “”
// matched: (2) [{…}, {…}]
// meta: {}
// name: “Home”
// params: {}
// path: “/”
// query: {}

//导航守卫
router.beforeEach((to, from, next) => {
//判断你跳转的路径
  if(to.path === '/'){
	//做一些token的判断
	const tokenObj = store.state.tokenObj//这一步可有可无
	//这里判断token是否存在
	if( tokenObj && tokenObj.token){
		//存在,放行调用next
		next()
	}else{
		//其他情况放行
		next()
	}
  }
})

但是这样不够,我们会出现一个小bug
在跳转到/uesr的时候我们清空token,登录再进/user就不会出现下面这个错误

出错
可加一下代码到顶部:

//缓存原有的push方法
const originalPush = VueRouter.prototype.push
//重写了push方法
VueRouter.prototype.push = function push (location) {
  //先执行原有的方法,保持功能不变
  return originalPush.call(this, location).catch(err => err)
}

多个导航守卫:

//导航守卫
router.beforeEach((to, from, next) => {
	const permissionList = ['/user','/video','/edit']
	if(permissionList.includes(to.path)){
	   //做一些token的判断
	const tokenObj = store.state.tokenObj//这一步可有可无
	//这里判断token是否存在
	if( tokenObj && tokenObj.token){
	//存在,放行调用next
	next()
	} else {
	   // 不需要做判断 
	   next()
	}
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值