reset router使用的方法是更换matcher,解释如下:
// 替换现有router的routes
router.matcher = new VueRouter({
routes: newRoutes
}).matcher
router.matcher是比较核心的一个属性。对外提供两个方法match(负责route匹配) 和 addRoutes(动态添加路由)。
具体原因:在做路径切换transitionTo方法中,首先就会使用const route = this.router.match(location, this.current)来匹配route, 其实内部会使用matcher来做匹配。修改了matcher即新的routes生效。
match (
raw: RawLocation,
current?: Route,
redirectedFrom?: Location
): Route {
// 这里使用matcher的match方法来做匹配
return this.matcher.match(raw, current, redirectedFrom)
}
//对router.matcher属性做修改,即新的routes就会替换老的routes, 其实就是replaceRoutes()的含义(但是官方没有提供这个API)。
export type Matcher = {
match: (raw: RawLocation, current?: Route, redirectedFrom?: Location) => Route;
addRoutes: (routes: Array<RouteConfig>) => void;
};