路由守卫
路由前置守卫beforeEach
路由在每次切换之前,都会到用一个函数:beforeEach
举个简单的栗子:如果当前跳转的路由路径是/home或者/about时才能查看页面,否则提示无权限:
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/home',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: () => import('../views/About.vue')
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
//全局配置路由守卫,初始化被调用、每次路由切换被调用
router.beforeEach((to,from,next)=>{
//要到哪去to 从哪来from
if(to.path==="/home"||to.path==="/about"){
if(localStorage.getItem('user')){
next()//调用next才会往下走
}
}else{
alert("无权限")
}
})
export default router
上面这种方法只适合做简单的路由处理,如果是项目中的路由权限判断,推荐使用路由原信息
这种方式:
路由原信息:
router中提供的一个路由配置项meta,里面可以自定义任意信息,自定义的属性可以在路由地址和导航守卫中被访问到
- 配置路由时,给每一项加上一个属性,用来控制路由的权限
const routes = [
{
path: '/home',
name: 'Home',
component: Home,
meta:{
// 只有经过身份验证的用户才能访问
isAuth: true
}
},
{
path: '/about',
name: 'About',
component: () => import('../views/About.vue'),
meta:{
// 任何人都可以访问此页面
isAuth: false
}
}
]
- 权限验证
router.beforeEach((to,from,next)=>{
//要到哪去to 从哪来from
if(to.meta.isAuth){
if(localStorage.getItem('user')){
next()//调用next才会往下走
}
}else{
alert("无权限")
}
})
路由后置守卫afterEach
既然有前置路由守卫beforeEach
,当然也有后置路由守卫afterEach
,实际项目中用的并不多
afterEach
只有两个参数,to
和from
举个栗子:我们想实现这样一个功能,让网页标签的title,随着页面的改变而改变:
const routes = [
{
path: '/home',
name: 'Home',
component: Home,
meta:{
// 只有经过身份验证的用户才能访问
isAuth: true,
title:"首页"
}
},
{
path: '/about',
name: 'About',
component: About,
meta:{
// 任何人都可以访问此页面
isAuth: false,
title:"关于"
},
children:[
{
path: '/detail',
name: 'Detail',
component: Detail,
meta:{
// 任何人都可以访问此页面
isAuth: false,
title:"详情"
},
}
]
}
]
router.afterEach((to,from)=>{
document.title = to.meta.title||'默认标题'
})