动态路由匹配
### 笔记
1. 路由跳转3种
- RouterLink给to属性指定地址进行跳转
- dom元素中,事件中使用`$router.push('/')
- js编程方式跳转:
1. js中先拿到路由实例
2. router.push()
#### 动态路由匹配
```js
const User = {
template: '<div>User {{ $route.params.id }}</div>'
}
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User }
]
})
```
#### 响应路由参数的变化
1. **使用 `watch` 监听 `$route` 对象**:
```js
const User = {
template: '...',
watch: {
$route(to, from) {
// 对路由变化作出响应
console.log('路由参数变化:', to.params);
}
}
}
```
2. **使用 `beforeRouteUpdate` 导航守卫**(Vue Router 2.2+):
```js
const User = {
template: '...',
beforeRouteUpdate(to, from, next) {
// 在路由更新前响应变化
console.log('路由更新:', to.params);
next();
}
}
```
#### 使用通配符 `*` 来捕获所有路由或设置 404 页面。
```js
const routes = [
{
path: '/:pathMatch(.*)', // 捕获所有路由
name: 'NotFound',
component: NotFound
},
{
path: '/user-*', // 匹配以 `/user-` 开头的任意路径
component: UserGeneric
}
];
```
- **通配符路由**:`path: '*'` 通常用于客户端 404 错误。
- **`pathMatch` 参数**:通配符匹配的部分会自动添加到 `$route.params.pathMatch` 中。
```js
this.$router.push('/user-admin');
console.log(this.$route.params.pathMatch); // 'admin'
this.$router.push('/non-existing');
console.log(this.$route.params.pathMatch); // '/non-existing'
```
#### 高级匹配模式
- Vue Router 支持许多高级匹配模式,如可选参数、零或多个参数、一个或多个参数,甚至自定义的正则匹配规则
```js
const routes = [
{
path: '/chapters*', // 匹配 `/chapters`, `/chapters/one`, `/chapters/one/two`, 等
component: Chapters
},
{
path: '/chapters+', // 匹配 `/chapters/one`, `/chapters/one/two`, 等,但不匹配 `/chapters`
component: Chapters
},
{
path: '/users/:id?', // 可选参数,匹配 `/users` 和 `/users/42`
component: Users
}
];
```