动态路由匹配
动态路径参数使用冒号 : 标记
把某种模式匹配到的所有路由,全都映射到同个组件可以在路由 path 选项中使用
const User = { template: '<div>User</div>' }
const router = new VueRouter({
routes: [{
path: '/user/:id', /* 动态路径参数 以冒号开头 */
component: User
}]
})
匹配到路由时,参数会被设置到 this.$route.params,在每个组件内用
const User = { template: '<div>User {{ $route.params.id }}</div>' }
路由中设置多段"路径参数",对应的值都会设置到 $route.params 中
/user/:username
console.log( $route.params ) => { username: 'evan' }
/user/:username/post/:post_id
console.log( $route.params ) => { username: 'evan', post_id: '123' }
响应路由参数的变化
当使用路由参数时,原来的组件实例会被复用( /user/foo 导航 /user/bar ),因为两个路由都渲染同个组件,复用显得更高效,这也意味组件的生命周期钩子不会被调用。复用组件时,想对路由参数的变化作出响应的话,可以简单地 watch (监测变化) $route 对象或者在组件内使用 beforeRouteUpdate 路由钩子函数
/* wacth 侦听 $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()
}
}
通配符 (*):
捕获所有路由或 404 Not found 路由,匹配任意路径
含有通配符的路由要放在最后
path: '*', /* 匹配所有路径 */
path: '/user-*', /* 匹配以 `/user-` 开头的任意路径 */
使用通配符时,$route.params 会自动添加名为 pathMatch 参数。包含通配符匹配的部分
{ path: '/user-*' }
this.$router.push('/user-admin')
this.$route.params.pathMatch // 'admin'
this.$router.push('/non-existing')
this.$route.params.pathMatch // '/non-existing'
匹配优先级
同一个路径可以匹配多个路由,匹配的优先级就按照路由的定义顺序:谁先定义的,谁的优先级就最高
高级匹配模式
vue-router 使用 path-to-regexp 作为路径匹配引擎,所以支持很多高级的匹配模式,例如:可选的动态路径参数、匹配零个或多个、一个或多个,甚至是自定义正则匹配。
路由对象
路由对象 (route object) 表示当前激活的路由的状态信息
路由对象是不可变 (immutable) 的,每次成功的导航后都会产生新的对象
路由对象出现在多个地方
1、在组件内,即 this.$route
2、在 $route 观察者回调内 => router.match(location) 的返回值
3、导航守卫的参数
/* to 和 from 都是路由对象 */
router.beforeEach((to, from, next) => {})
4、scrollBehavior 方法的参数
const router = new VueRouter({
/* to 和 from 都是路由对象 */
scrollBehavior (to, from, savedPosition) {}
})