# matcher
matcher 相关的实现都在 src/create-matcher.js 中,我们先来看一下 matcher 的数据结构:
export type Matcher = {
match: (raw: RawLocation, current?: Route, redirectedFrom?: Location) => Route;
addRoutes: (routes: Array<RouteConfig>) => void;
};
@前端进阶之旅: 代码已经复制到剪贴板
Matcher 返回了 2 个方法,match 和 addRoutes,在上一节我们接触到了 match 方法,顾名思义它是做匹配,那么匹配的是什么,在介绍之前,我们先了解路由中重要的 2 个概念,Loaction 和 Route,它们的数据结构定义在 flow/declarations.js 中。
- Location
declare type Location = {
_normalized?: boolean;
name?: string;
path?: string;
hash?: string;
query?: Dictionary<string>;
params?: Dictionary<string>;
append?: boolean;
replace?: boolean;
}
@前端进阶之旅: 代码已经复制到剪贴板
Vue-Router 中定义的 Location 数据结构和浏览器提供的 window.location 部分结构有点类似,它们都是对 url 的结构化描述。举个例子:/abc?foo=bar&baz=qux#hello,它的 path 是 /abc,query 是 {foo:'bar',baz:'qux'}。Location 的其他属性我们之后会介绍。
- Route
declare type Route = {
path: string;
name: ?string;
hash: string;
query: Dictionary<string>;
params: Dictionary<string>;
fullPath: string;
matched: Array<RouteRecord>;
redirectedFrom?: string;
meta?: any;
}
@前端进阶之旅: 代码已经复制到剪贴板
Route 表示的是路由中的一条线路,它除了描述了类似 Loctaion 的 path、query、hash 这些概念,还有 matched 表示匹配到的所有的 RouteRecord。Route 的其他属性我们之后会介绍。
# createMatcher
在了解了 Location 和 Route 后,我们来看一下 matcher 的创建过程:
export function createMatcher (
routes: Array<RouteConfig>,
router: VueRouter
): 