导航守卫
所谓导航守卫,就是在路由跳转时对路由进行拦截,然后改变跳转方向的相关方法
路由信息对象
组件中获取路由信息对象使用 this.$route
,在导航守卫中有 to
, from
,这两个分别代表要跳转的路由信息对象,和跳转前的路由信息对象
全局前置守卫
// router就是new VueRouter()
router.beforeEach((to, from, next) => {
next() // 如果不写next()则所有都无法正常跳转
})
next()
next是进行路由导航的一个方法,它等同于 this.$router.push
,语法和 push
一样
如果我们在导航守卫中,想要让路由进行挑战,则使用next,具体跳转到哪个位置,需要看具体的需求
路由拦截
路由拦截一般会使用全局前置守卫进行全局拦截
/*
要求 page1 和 page2 都需要拦截
1 设置导航守卫
*/
const routes = [
{
path: '/'
},
{
path: '/page',
meta: {
auth: true
}
},
{
path: '/page2',
meta: {
auth: true
}
},
{
path: '/login'
}
]
const router = new VueRouter({
routes
})
router.beforeEach((to, from, next) => {
if (to.matched.some(route => route.meta.auth)) {
// 判断是否登录
if (isLogin) {
next()
} else {
next('/login')
}
} else {
next()
}
})
matched
matched属于路由信息对象,是一个数组。这个数组包含了该路由中所有的父路由及祖先路由。
小明 -> 父亲 -> 爷爷 -> 祖先
其他守卫
全局守卫
- beforeEach
- beforeResolve
- afterEach
路由独享守卫
- beforeEnter
组件内守卫
- beforeRouteEnter
- beforeRouteUpdate
- beforeRouteLeave
除了afterEach外,其他都需要添加next() 不然路由就不能正常跳转