全局路由守卫与独享路由守卫
meta
:路由元信息
通过meta对象中的一些属性来判断当前路由是否需要进一步处理,如果需要处理,按照自己想要的效果进行处理即可
import {createRouter, createWebHashHistory} from "vue-router";
const routes=[
{
path:'/home',
component:()=>import('@/pages/home'),
meta:{
isAuth:true,
title:'首页'
},
},
{
path: '/about',
component:()=>import('@/pages/about'),
meta:{
isAuth:true,
title:'关于'
},
//独享路由守卫
beforeEnter(to,from,next){
console.log(to,from)
if(to.meta.isAuth){ //判断是否需要鉴权
if(localStorage.getItem('school') === 'atguigu'){
next()
} else {
alert('学校名不对,无权查看!')
}
}
},
children:[
{
path: 'mine',
component:()=>import('@/pages/mine'),
meta:{
isAuth:true,
title:'我的'
},
},
]
},
{
path: '/query',
component:()=>import('@/pages/query'),
meta:{
isAuth:true,
title:'query'
},
},
{
path: '/params/:id/:title/:content',
name:'params',
component:()=>import('@/pages/params'),
meta:{
isAuth:true,
title:'params'
},
},
{
// path: '/props/:id/:title/:content',//params方式
path: '/props',//query方式
name:'props',
component:()=>import('@/pages/props'),
meta:{
isAuth:true,
title:'props'
},
// props的第一种写法,值为对象,该对象中的所有Key-value都会以props的形式传递给Dateil组件
// props:{a:1,b:'hello'}
// props的第二种写法,值为布尔值,若布尔值为真,就会把该路由组件收到的所有params参数,以props的形式传给Detail组件
// props:true
// props的第三种写法,值为函数==>params方式
// props({params:{id,title,content}}){
// return {id,title,content}
// }
// props的第三种写法,值为函数==>query方式
props({query:{id,title,content}}){
return {id,title,content}
}
},
{
path: '/:pathMatch(.*)*',
redirect:'/home'
}
]
const router=createRouter({
history:createWebHashHistory(),
routes
})
// 全局前置路由守卫 ----- 初始化的时候被调用,每次路由切换之前被调用
router.beforeEach((to,from,next)=>{
console.log(to,from)
if(to.meta.isAuth){ //判断是否需要鉴权
if(localStorage.getItem('school') === 'atguigu'){
next()
} else {
alert('学校名不对,无权查看!')
}
}
})
// 全局后置路由守卫 ----- 初始化的时候被调用,每次路由切换之后前被调用
router.beforeEach((to,from)=>{
console.log('后置路由守卫',to,from)
document.title = to.meta.title || '硅谷系统'
})
export default router
路由守卫
1.作用:对路由进行权限控制
2.分类:全局守卫,独享守卫,组件内守卫
3.全局守卫
// 全局前置守卫,初始化时执行,每次路由切换前执行
router.beforeEach((to,from,next)=>{
console.log('beforeEach',to,from)
if(to.meta.isAuth){ //判断当前路由是否需要进行权限控制
if(localStorage.getItem('school') === 'atguigu'){ //权限控制的具体规则
next() // 放行
} else {
alert('暂无权限查看!')
}
} else {
next() // 放行
}
})
//全局后置守卫,初始化时执行,每次路由切换后执行
router.alterEach((to,from)=>{
console.log('afterEach',to,from)
if(to.meta.title){
document.title = to.meta.title //修改网页的title
} else {
document.title = 'vue_test'
}
})
4.独享守卫
beforeEnter(to,from,next){
console.log('beforeEnter',to,from)
if(to.meta.isAuth){ //判断当前路由是否需要进行权限控制
if(localStorage.getItem('school') === 'atguigu'){ //权限控制的具体规则
next() // 放行
} else {
alert('暂无权限查看!')
}
} else {
next() // 放行
}
}
5.组件内守卫
// 进入守卫:通过路由规则,进入该组件时被调用
beforeRouteEnter(to,from,next){
}
// 离开守卫,通过路由规则,离开该组件时被调用
beforeRouteLeave(to,from,next){
}