官网
直接粘贴复制
//导航守卫
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()
}
})