1、active-class是哪个组件的属性?嵌套路由怎么定义?
vue-router模块的router-link组件提供的。vue-router的嵌套路由由children数组来实现。
2、vue-router如何响应 路由参数 的变化?
当使用路由参数时,例如从 /content?id=1 到 content?id=2,此时原来的组件实例会被复用。这也意味着组件的生命周期钩子不会再被调用,此时vue应该如何响应路由参数 的变化?
- 可以watch ( 监测变化 ) $route 对象。
const User = {
template: '...',
watch: {
'$route' (to, from) {
// 对路由变化作出响应...
}
}
}
- beforeRouteUpdate 守卫。
const User = {
template: '...',
beforeRouteUpdate (to, from, next) {
// react to route changes...
// don't forget to call next()
}
}
- 完整的
vue-router导航解析流程。 1、导航被触发。
2、在失活的组件里调用离开守卫。
3、调用全局的beforeEach守卫。
4、在重用的组件里调用beforeRouteUpdate守卫 (2.2+)。
5、在路由配置里调用beforeEnter。
6、解析异步路由组件。
7、在被激活的组件里调用beforeRouteEnter。
8、调用全局的beforeResole守卫 (2.5+)。
9、导航被确认。
10、调用全局的afterEach钩子。
11、触发DOM更新。
12、用创建好的实例调用beforeRouteEnter守卫中传给next的回调函数。
3、 vue-router有哪几种导航钩子( 导航守卫 )?
1、全局守卫:
router.beforeEach每个守卫方法接收三个参数:
to: Route:即将要进入的目标 路由对象
from: Route: 当前导航正要离开的路由next: Function:一定要调用该方法来resolve这个钩子。执行效果依赖 next 方法的调用参数。
const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
// ...
})
2、全局解析守卫:
router.beforeResolve在 2.5.0+ 你可以用router.beforeResolve注册一个全局守卫。这和router.beforeEach类似,区别是:在导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后,解析守卫就被调用。
3、全局后置钩子:
router.afterEach你也可以注册全局后置钩子,然而和守卫不同的是,这些钩子不会接受 next 函数也不会改变导航本身:
router.afterEach((to, from) => {
// ...
})
4、路由独享的守卫:
beforeEnter你可以在路由配置上直接定义 beforeEnter 守卫:
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
// ...
}
}
]
})
5、组件内的守卫:
beforeRouteEnter、beforeRouteUpdate(2.2 新增)、beforeRouteLeave注意:beforeRouteEnter 是支持给next 传递回调的唯一守卫。对于beforeRouteUpdate 和 beforeRouteLeave 来说,this 已经可用了,所以不支持传递回调,因为没有必要了: