关于vue-router的*号匹配问题
vue-router的匹配规则是从上向下,匹配到就不继续向下匹配了,但是最近发现了一个问题
// 定义路由规则的数组
const routes = [
{
path: '*',
component: NotFound
},
{
path: '/',
redirect: '/find', // 重定向到/find
},
{
path: '/find',
name: 'Find',
component: Find,
},
{
path: '/my',
name: 'My',
component: My
},
]
现在我把 * 上放到了最上面,但是vue-router并没有直接匹配*,于是我很好奇,就打开了vue-router的源码
源码位置在 vue-router/src/create-route-map.js
// ensure wildcard routes are always at the end
for (let i = 0, l = pathList.length; i < l; i++) {
if (pathList[i] === '*') {
pathList.push(pathList.splice(i, 1)[0])
l--
i--
}
}
可以看到,处理路径时,如果碰到 * ,就把 * 放到 pathList 的末尾,所以我们可以知道了,如果你 path 写了 * ,vue-router 会帮你把此路径排到末尾

浙公网安备 33010602011771号