路由守卫(导航守卫):
1:全局钩子: beforeEach、 afterEach
2:独享守卫(单个路由里面的钩子): beforeEnter
3:组件守卫:beforeRouteEnter、 beforeRouteUpdate、 beforeRouteLeave
全局路由守卫
- 全局前置路由守卫 :router.beforeEach(to,from,next) 初始化的时候被调用、每次路由切换之前被调用
- 全局后置路由守卫 :router.afterEach(to,from) 初始化的时候被调用、每次路由切换之后被调用
独享路由守卫
- beforeEnter(to,from,next) 初始化的时候被调用、每次路由进入之前被调用,仅作用域该组件
组件路由守卫
- beforeRouteEnter(to,from,next) 通过路由规则,进入该组件时被调用
- beforeRouteLeave(to,from,next) 通过路由规则,离开该组件时被调用
配置项:
//需要配置路由守卫时,需要配置 meta: { isAuth: true }
{
path: '/',
name: 'Home',
component: () => import('../views/Home.vue'),
meta: { isAuth: true, title:'主页' },
},
全局前置路由守卫代码:
//全局前置路由守卫————初始化的时候被调用、每次路由切换之前被调用
router.beforeEach((to, from, next) => {
//如果路由需要跳转
if (to.meta.isAuth) {
//判断 如果school本地存储是qinghuadaxue的时候,可以进去
if (localStorage.getItem('school') === 'qinghuadaxue') {
next() //放行
} else {
alert('抱歉,您无权限查看!')
}
} else {
// 否则,放行
next()
}
})
全局后置路由代码:
//全局后置路由守卫————初始化的时候被调用、每次路由切换之后被调用
router.afterEach((to, from) => {
document.title = to.meta.title || '默认名' //修改网页的title
})
独享路由(与全局前置路由基本相同,只作用于当前路由):
{
path: '/',
name: 'Home',
component: () => import('../views/Home.vue'),
meta: { isAuth: true },
beforeEnter: (to, from, next) => {
if (to.meta.isAuth) { //判断是否需要授权
if (localStorage.getItem('school') === 'qinghuadaxue') {
next() //放行
} else {
alert('抱歉,您无权限查看!')
}
} else {
next() //放行
}
}
},
组件路由守卫:
//通过路由规则,进入该组件时被调用
beforeRouteEnter(to,from,next) {
if(toString.meta.isAuth){
if(localStorage.getTime('school')==='qinghuadaxue'){
next()
}else{
alert('学校名不对,无权限查看!')
}
} else{
next()
}
},
//通过路由规则,离开该组件时被调用
beforeRouteLeave(to,from,next) {
next()
}