时间:2022-08-23 10:23:28 | 栏目:vue | 点击:次
了解相关的几个概念
对url的结构化描述。比如url = “/main?p1=1&p2=2222&p3=3333”,它的path就是“ /main” , query 是{ p1:1, p2:222, p3:333 }
declare type Location = {
_normalized?: boolean;
name?: string;
path?: string;
hash?: string;
query?: Dictionary<string>;
params?: Dictionary<string>;
append?: boolean;
replace?: boolean;
}
declare type RawLocation = string | Location //除了是Location类型还可以是字符串
表示一条路由,属性也包括path、query、hash等。重要的是mached它表示匹配到的所有的 RouteRecord 对象。
declare type Route = {
path: string;
name: ?string;
hash: string;
query: Dictionary<string>;
params: Dictionary<string>;
fullPath: string;
matched: Array<RouteRecord>;
redirectedFrom?: string;
meta?: any;
}
declare type RouteRecord = {
path: string;
regex: RouteRegExp;
components: Dictionary<any>;
instances: Dictionary<any>; //表示组件的实例 一个对象类型
name: ?string;
parent: ?RouteRecord; //表示父的 RouteRecord
redirect: ?RedirectOption;
matchAs: ?string;
beforeEnter: ?NavigationGuard;
meta: any;
props: boolean | Object | Function | Dictionary<boolean | Object | Function>;
}
matcher对象对外提供 match() 和 addRoutes()两个方法。addRoutes() 作用是动态添加路由配置。match() 根据传入的rawLoction类型的raw 和当前的路径 currentRoute 计算出一个新的路径并返回。//记录path 及 path到RouteRecord的映射
if (!pathMap[record.path]) {
pathList.push(record.path) // ['/aaa/bbb','/cccc/ddd']
pathMap[record.path] = record //path值作为key
// /aaa/bbb:{ path:"/aaa/bbb" ,regex : //}
}
pathMap值示例

//记录name到RouteRecord的映射; name值作为key
if (name) {
if (!nameMap[name]) {
nameMap[name] = record
} else if (process.env.NODE_ENV !== 'production' && !matchAs) {
warn(
false,
`Duplicate named routes definition: ` +
`{ name: "${name}", path: "${record.path}" }`
)
}
}
得到的这些map是为了路由匹配做了基础。
作用是匹配一个路径并找到映射的组件。
执行过程
在VueRouter中,所有的Route 最终都是通过 createRoute 函数创建,并且它最后是不可以被外部修改的。 Route对象中有一个重要属性 matched,它通过 formatMatch(record) 计算得到:
function formatMatch (record: ?RouteRecord): Array<RouteRecord> {
const res = []
while (record) {
res.unshift(record)
record = record.parent
}
return res
}
record循环往上找parent,直到找到最外层。把所有的record都放到一个数组里面,它记录了一条线路上的所有record。matched属性为之后渲染组件提供了依据。