当前位置: 首页 > Web前端 > vue.js

【vue-router源码】五、addRoute-removeRoute-hasRoute-getRoutes源码分析

时间:2023-03-31 23:18:29 vue.js

前言【vue-router源码】系列文章带你从0开始了解vue-router的具体实现。本系列文章源码参考vue-routerv4.0.15。源码地址:https://github.com/vuejs/router阅读本文的前提是你最好了解vue-router的基本使用。如果没有使用过,可以通过vue-router官网进行学习。本文将分析router.addRoute、router.removeRoute、router.hasRoute、router.getRoutes的实现。使用addRoute使用addRoute添加路由时,如果第一个参数是路由名称,则添加一个嵌套路由;否则,将添加一个非嵌套路由。//添加一个非嵌套路由router.addRoute({name:'admin',path:'/admin',component:Admin})//添加一个嵌套路由router.addRoute('admin',{path:'settings',component:AdminSettings})以上代码等同于:router.addRoute({name:'admin',path:'/admin',component:Admin,children:[{path:'settings',component:AdminSettings}],})removeRouterouter.removeRoute('admin')hasRouterouter.hasRoute('admin')getRouterouter.getRoutes()addRouteaddRoute接受两个参数:parentOrRoute(父路由或者新路由的名字,如果是路由的名字parentroute,namefirst需要两个参数),record(要添加的路由)。返回删除新添加路由的函数。functionaddRoute(parentOrRoute:RouteRecordName|RouteRecordRaw,route?:RouteRecordRaw){letparent:Parameters[1]|复制代码undefinedletrecord:RouteRecordRaw//如果parentOrRoute是路由名,parent就是parentOrRoute匹配器对应的,添加的路由是嵌套路由if(isRouteName(parentOrRoute)){parent=matcher.getRecordMatcher(parentOrRoute)record=route!}else{//如果parentOrRoute不是路由名,则parentOrRoute为要添加的路由record=parentOrRoute}//调用matcher.addRoute添加一条新记录,返回一个函数移除路由returnmatcher.addRoute(record,parent)}定义父级时,使用Paramerer类型。该类型的使用参考https://www.typescriptlang.org/docs/handbook/utility-types.html#parameterstype。在此方法中,parent的类型将采用matcher.addRoute方法中第二个参数的类型。isRouteName:通过判断名称是字符串还是符号类型来判断是否是routeName。导出函数isRouteName(name:any):nameisRouteRecordName{returntypeofname==='string'||typeofname==='symbol'}removeRoute删除路由。removeRoute采用名称(现有路由的名称)参数。functionremoveRoute(name:RouteRecordName){//根据name获取对应的routeRecordMatcherconstrecordMatcher=matcher.getRecordMatcher(name)if(recordMatcher){//如果有recordMatcher,调用matcher.removeRoutematcher.removeRoute(recordMatcher)}elseif(__DEV__){warn(`Cannotremovenon-existentroute"${String(name)}"`)}}hasRoute用于判断路由是否存在。hasRoute接收一个名称字符串并返回一个布尔值。使用matcher.getRecordMatcher获取对应的匹配器。在matcher.getRecordMatcher中,你会在matcherMap中找到对应的matcher。如果没有找到,说明该路由不存在。functionhasRoute(name:RouteRecordName):boolean{return!!matcher.getRecordMatcher(name)}getRoutes获取标准化路由列表。规范化的路由将存储在matcher.record中。functiongetRoutes(){//遍历匹配器,路由的标准化版本存储在routeMatcher.record中returnmatcher.getRoutes().map(routeMatcher=>routeMatcher.record)}Summaryrouter.addRoute,router.removeRoute,router.hasRoute、router.getRoutes的几个API都依赖matcher实现。可见matcher是vue-router的核心。如果对匹配器不了解,建议复习一下上一篇。