Appearance
路由的匹配语法
大多数应用都会使用 /about 这样的静态路由和 /users/:userId 这样的动态路由,就像我们刚才在动态路由匹配中看到的那样,但是 Vue Router 可以提供更多的方式!
在参数中自定义正则
| URL | 路由规则 | 组件 |
|---|---|---|
| client/:123 | 匹配 /:orderId(\d+) | OrderDetail.vue |
| client/:user-john | 匹配 /:username(user-.+) | UserProfile.vue |
| client/:awesome-book | 匹配 /:productSlug | ProductDetail.vue |
在动态参数路中中使用正则的目的是在路由层就进行分流,核心作用是分流而不是复用
复用
javascript
// 例如:不同ID的订单使用同一个组件
{
path: '/orders/:id', // /orders/1 和 /orders/2
component: OrderDetail // 相同组件处理不同ID
}javascript
// 产品详情页的不同标签页
{
path: '/products/:id/:tab(reviews|specs)',
component: ProductDetail
}javascript
// 同一组件渲染不同类型的CMS内容块
{
path: '/content/:contentType/:contentId',
component: DynamicContent
}分流
javascript
{
path: '/:orderId(\\d+)', // 数字 → 订单
component: OrderDetail // 相同组件处理不同ID
},
{
path: '/:productSlug', // 字符串 → 产品
component: PruductDetail // 相同组件处理不同ID
}可重复的参数
如果你需要匹配具有多个部分的路由,如 /first/second/third,你应该用 *(0 个或多个)和 +(1 个或多个)将参数标记为可重复:
javascript
const routes = [
// /:chapters -> 匹配 /one, /one/two, /one/two/three, 等
{ path: '/:userName+' },
// /:chapters -> 匹配 /, /one, /one/two, /one/two/three, 等
{ path: '/:userName*' },
]这里在获取route参数时,route.params会返回一个数组
json
{ "userName": ["more", "1", "2", "3"] }这些也可通过在右括号添加自定义正则结合使用
javascript
const routes = [
// 仅匹配数字
// 匹配 /1, /1/2, 等
{ path: '/:chapters(\\d+)+' },
// 匹配 /, /1, /1/2, 等
{ path: '/:chapters(\\d+)*' },
]Sensitive 与 Strict 路由配置
默认情况下,所有路由时不分大小写的,并且能匹配带有或不带尾部斜线的路由.比如,路由/users将匹配/users,/users/,/Users等.这种行为可以通过strict和sensitive配置选项来改变
javascript
const router = createRouter({
history: createWebHistory(),
routes: [
// 将匹配 /users/posva 而非:
// - /users/posva/ 当 strict: true
// - /Users/posva 当 sensitive: true
{ path: '/users/:id', sensitive: true },
// 将匹配 /users, /Users, 以及 /users/42 而非 /users/ 或 /users/42/
{ path: '/users/:id?' },
],
strict: true, // applies to all routes
})可选参数
可以通过?在参数后面来表示该参数是可选的
javascript
const routes = [
// 匹配 /users 和 /users/posva
{ path: '/users/:userId?' },
// 匹配 /users 和 /users/42
{ path: '/users/:userId(\\d+)?' },
]