路由守卫
当路由切换时,判断权限
路由守卫类型
1.全局守卫
2.独享守卫
3.组件内守卫
1.全局守卫
1.前置路由守卫 全局前置路由守卫————初始化的时候被调用、每次路由切换之前被调用
在需要加上路由守卫的路由配置中加上
meta:{isAuth:true}
{path: '/',name: 'Home',component: () => import('../views/Home.vue'),meta: { isAuth: true, title:'主页' },},
//全局前置路由守卫————初始化的时候被调用、每次路由切换之前被调用
router.beforeEach((to, from, next) => {//如果路由需要验证if (to.meta.isAuth) {if (localStorage.getItem('123') === '123') {next() //放行} else {alert('抱歉,您无权限查看!')}} else {// 否则,放行next()}
})
2.后置路由守卫 ,路由跳转之后执行的事件,一般用作跳转路由后更改网页名
{path: '/',name: 'Home',component: () => import('../views/Home.vue'),meta: { isAuth: true, title:'主页' },},
//全局后置路由守卫————初始化的时候被调用、每次路由切换之后被调用
router.afterEach((to, from) => {document.title = to.meta.title || '默认名' //修改网页的title
})
3.独享路由守卫,某一个路由所单独享用的路由守卫,独享路由守卫只有前置没有后置
{path: '/',name: 'Home',component: () => import('../views/Home.vue'),meta: { isAuth: true },beforeEnter: (to, from, next) => {if (to.meta.isAuth) { //判断是否需要授权if (localStorage.getItem('123') === '123') {next() //放行} else {alert('抱歉,您无权限查看!')}} else {next() //放行}}},
4.组件内守卫
//通过路由规则,进入该组件时被调用
beforeRouteEnter(to,from,next) {if(toString.meta.isAuth){if(localStorage.getTime('123')==='123'){next()}else{alert('无权限查看!')}} else{next()}
},//通过路由规则,离开该组件时被调用
beforeRouteLeave(to,from,next) {next()
}