vue/router 版本 4.3.2

vue-router是如何处理props的

我们在使用vue-router时主要使用的两个方法是

1
2
createrouter(options)
createWebHistory()

createrouter 接收的参数包括 routes, history 等

在 createrouter 中首先会调用 createRouterMatcher 返回一个matcher,

createRouterMatcher的参数为options.routes和options,
在这个方法中首先会定义一个变量

1
const matchers = [];

拿到routes之后,遍历routes,执行addRoute操作,每一个参数就是我们配置的一个route,源码中叫record,它有3个参数,当前的rocord,parent,originalRecord,
通过第三个参数来判断,是否在处理root节点的路由

1
const isRootAdd = !originalRecord;

然后调用normalizeRouteRecord来处理record

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function normalizeRouteRecord(record) {
return {
path: record.path,
redirect: record.redirect,
name: record.name,
meta: record.meta || {},
aliasOf: undefined,
beforeEnter: record.beforeEnter,
props: normalizeRecordProps(record),
children: record.children || [],
instances: {},
leaveGuards: new Set(),
updateGuards: new Set(),
enterCallbacks: {},
components: 'components' in record
? record.components || null
: record.component && { default: record.component },
};
}

可以看到props在这里被处理了一次,但这里只是简单的处理,
当record传递了props时,如果record中配置了component,就产生一个对象

1
2
3
{
default: 值为我们传递的props || false
}

并把这个对象赋值给原本的props,如果我们没有传component,则会遍历record中的components,每一项都会经过判断后赋予props,如果我们传的props是对象,就根据每一项去单独取props,否则,直接赋予我们传递的props

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function normalizeRecordProps(record) {
const propsObject = {};
// props does not exist on redirect records, but we can set false directly
const props = record.props || false;
if ('component' in record) {
propsObject.default = props;
}
else {
// NOTE: we could also allow a function to be applied to every component.
// Would need user feedback for use cases
for (const name in record.components)
propsObject[name] = typeof props === 'object' ? props[name] : props;
}
return propsObject;
}

然后会对当前record的children坐同样的处理

vue-router对我们配置的单个路由做了什么处理

首先会对每一个路由判断,如果此路由有parent路由且parent路由有name,但此路由的name和path都为空,则抛出警告。