首页

源码搜藏网

首页 > 开发教程 > js/jQuery教程 >

Vue,Router中Matcher的初始化流程

创建时间:2022-04-15 10:31  

Matcher

createMatcher()的初始化

了解相关的几个概念

1、Location类型

对url的结构化描述。比如url = “/mainp1=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;
}

2、rowLocation类型

declare type RawLocation = string | Location //除了是Location类型还可以是字符串

3、Route类型

表示一条路由,属性也包括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;
}

4、RouteRecord类型

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>;
}

addRoutes()的实现

//记录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值示例

Vue,Router中Matcher的初始化流程

//记录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是为了路由匹配做了基础。

match()

作用是匹配一个路径并找到映射的组件。

执行过程

matched属性

在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属性为之后渲染组件提供了依据。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持源码搜藏网。

上一篇:vue3限制table表格选项个数的解决办法
下一篇:没有了

相关内容

热门推荐