问题描述: push({name: 'testName'}) 报错` Error: No match for {"name":"/testName" } ;
- 造成这一问题的根本原因为
vue-router中push方法的执行, 源码如下: - 对于 name,它直接从 matcherMap 中获取匹配器,而对于 path,它则是通过正则表达式测试路径来获取匹配器。
if ('name' in location && location.name) {
matcher = matcherMap.get(location.name)
if (!matcher)
throw createRouterError<MatcherError>(ErrorTypes.MATCHER_NOT_FOUND, {
location,
})
// ....省略
}else if (location.path != null) {
path = location.path
matcher = matchers.find(m => m.re.test(path))
// matcher should have a value after the loop
if (matcher) {
// we know the matcher works because we tested the regexp
params = matcher.parse(path)!
name = matcher.record.name
}
}
解决方案:
- push时使用hasRouter先来判断
router.hasRoute('OrderLeaseDetailManage')
- 全局增加error监听
window.addEventListener('error', function (event) {
if (event.message.startsWith('Uncaught Error: No match for')) {}
});
- try catch块捕获router.push错误
try {
router.push({ name: 'home' });
} catch (error) {
console.error('Navigation error:', error);
}