Vue-Router进阶
导航守卫:
导航守卫,就是导航过程中各个阶段的钩子函数。分为全局导航守卫、路由导航守卫、组件导航守卫。以下分别进行讲解。
全局导航守卫:
全局导航守卫,就是在整个网页中,只要发生了路由的变化,都会触发。全局导航守卫主要包括两个函数,分别为:beforeEach
、afterEach
。
beforeEach:
在路由发生了改变,但是还没有成功跳转的时候会调用。示例代码如下:
var router = new VueRouter({
routes: [
{path: "/",component: index,name:"index"},
{path: "/account",component: account,name:"account"},
{path: "/order",component: order,name:"order"},
{path: "/login",component: login,name:"login"},
]
})
router.beforeEach(function(to,from,next){
const authRoutes = ['account','order']
if(authRoutes.indexOf(to.name) >= 0){
if(logined){
next()
}else{
next("/login")
}
}else if(to.name == 'login'){
if(logined){
next("/")
}
}else{
next()
}
})
afterEach:
路由已经改变完成后的函数。这个函数没有next
参数。因为页面已经完成了跳转。
router.afterEach(function(to,from){
console.log('to:',to);
console.log('from:',from);
})
路由导航守卫:
路由组件导航守卫,也就是定义在路由上的导航守卫。使用方式就是在定义路由的对象中,传递一个beforeEnter
参数。示例代码如下:
var router = new VueRouter({
routes: [
{path: "/login",component: login,name:"login",beforeEnter:function(to,from,next){
if(logined){
next("/")
}else{
next()
}
}},
]
})
组件导航守卫:
组件导航守卫,就是在组件中写守卫。也就是进入到这个组件之前会调用的方法。组件导航守卫大体上也是三个方法:beforeRouteEnter
、beforeRouteUpdate
、beforeRouteLeave
。以下分别进行讲解。
beforeRouteEnter:
在进入到组件之前调用的。示例代码如下:
beforeRouteEnter(to,from,next){
// 在渲染该组件的对应路由被 confirm 前调用
// 不!能!获取组件实例 `this`
// 因为当守卫执行前,组件实例还没被创建
console.log('to:',to);
console.log('from:',from);
next(vm => {
// 通过 `vm` 访问组件实例
console.log(vm.username);
})
}
beforeRouteUpdate:
beforeRouteUpdate(to,from,next){
// 在当前路由改变,但是该组件被复用时调用
// 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
// 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
// 可以访问组件实例 `this`
console.log('to:',to);
console.log('from:',from);
next()
}
beforeRouteLeave:
beforeRouteLeave(to,from,next){
// 导航离开该组件的对应路由时调用
// 可以访问组件实例 `this`
const answer = window.confirm('您确定要离开这个页面吗?')
if (answer) {
next()
} else {
next(false)
}
}
导航解析流程:
- 导航被触发。
- 在失活的组件里调用离开守卫。
- 调用全局的 beforeEach 守卫。
- 在重用的组件里调用 beforeRouteUpdate 守卫 (2.2+)。
- 在路由配置里调用 beforeEnter。
- 解析异步路由组件。
- 在被激活的组件里调用 beforeRouteEnter。
- 调用全局的 beforeResolve 守卫 (2.5+)。
- 导航被确认。
- 调用全局的 afterEach 钩子。
- 触发 DOM 更新。
- 用创建好的实例调用 beforeRouteEnter 守卫中传给 next 的回调函数。
路由元信息:
在定义路由的时候,我们可以通过传递meta
参数可以传递一些额外的信息。比如这个路由是需要登录后才能访问的,那么就可以在meta
中添加一个requireAuth:true
。示例代码如下:
let router = new VueRouter({
routes: [
{path: "/",component: index},
{path: "/profile/:userid",component: profile,meta:{requireAuth:true}},
{path: "/login",component: login}
]
})
router.beforeEach(function(to,from,next){
if(to.meta.requireAuth && !logined){
next('/login')
}else{
next()
}
})