Skip to content

路由匹配算法

Vue Router 的路径匹配语法基于 Express 风格,可以通过动态参数、正则表达式、修饰符(?*+)等方式实现更灵活的匹配。

正则

特性示例含义
动态参数/users/:id匹配任意值
自定义正则/:id(\\d+)仅匹配数字
可选参数/:id?可有可无
可重复参数/:tags*0 个或多个
可重复(至少一个)/:tags+1 个或多个
大小写敏感sensitive: true区分 /Users/users
严格匹配strict: true/users/users/

示例

路由定义示例路径是否匹配$route.params 结果说明
/users/:id/users/abc{ id: 'abc' }动态参数,匹配任意字符串
/users/:id(\\d+)/users/123{ id: '123' }使用正则,仅匹配数字
/users/:id(\\d+)/users/abc不匹配,因为不是数字
/users/:id?/users{}参数可选(没有 id 也行)
/users/:id?/users/tom{ id: 'tom' }有参数也可匹配
/files/:pathMatch*/files{ pathMatch: [] }* 表示 0 或多个路径片段
/files/:pathMatch*/files/a/b/c{ pathMatch: ['a','b','c'] }捕获多层路径(数组)
/category/:slug+/category/a{ slug: ['a'] }+ 表示至少一个路径片段
/category/:slug+/category/a/b{ slug: ['a','b'] }可匹配多个
/category/:slug+/category+ 不能为 0 个片段