一、全局路由守卫
在export路由之前配置beforeEach((to,from,next) => {})
const router = new VueRouter({
routes: [
……
]
})
// 全局前置路由守卫————初始化的时候被调用、每次路由切换之前被调用
router.beforeEach((to,from,next) => { //to为目的路由信息 from为起始路由信息
console.log(to,from)
//可在此添加一些限制条件
next() //放行
})
export default router
可在路由的meta中配置是否需要校验
routes: [
{
name: 'home',
path: '/home',
component: MyHome,
meta: {isAuth: true},
}
]
router.beforeEach((to,from,next) => { //to为目的路由信息 from为起始路由信息
if(to.meta.isAuth)
alert("hello")
else{
next()
}
console.log(to,from)
})
后置路由守卫afterEach((to,from) => {}) 做一些跳转成功后的操作 比如:修改标签页标题
routes: [
{
name: 'home',
path: '/home',
component: MyHome,
meta: {isAuth: true,title:'hello word'},
}
]
router.afterEach((to,from) => {
console.log("后置路由")
document.title = to.meta.title
})
二、独享路由守卫
配置路由时直接配置beforeEnter((to,from,next) => {})
独享路由只有前置路由
例如
routes: [
{
name: 'about',
path: '/about',
component: MyAbout,
beforeEnter((to,from,next) => { //to为目的路由信息 from为起始路由信息
console.log(to,from,next)
}
},
]
三、组件内路由
配置在组件文件里
beforeRouteEnter(to,from,next) 通过路由规则,进入该组件时调用
beforeRouteLeave(to,from,next) 通过路由规则,离开该组件时被调用
例如
<script>
export default {
name: 'MyAbout',
// 通过路由规则,进入该组件时调用
beforeRouteEnter(to,from,next) {
console.log(to,from)
next()
},
// 通过路由规则,离开该组件时被调用
beforeRouteLeave(to,from,next) {
console.log(to,from)
next()
}
}
</script>