hashchange --> match route --> set vm._route --> <router-view> render() --> render matched component
Vue.util.defineReactive(this, '_route', this._router.history.current)
this._routerRoot._route
, 触发setter
parent.$route
, 也就是间接的触发了this._routerRoot._route
的getter
。即进行了依赖搜集。this._routerRoot._route
的setter
触发时即会触发router-view
的渲染watcher
, 再次渲染, 而且此时拿到的路由组件也是最新的。本质上利用了vue的响应式属性,在route属性变动和router-view视图渲染之间创建关系。vue
route变动 => render从新渲染
node
parent.$route
为何就会被this._routerRoot._route
收集watcher在挂载router-view组件时,会生成一个watcher, router-view的render函数中又触发了_route的getter方法,那么此watcher就被收集到_route的Dep中了。git
在_route的setter触发时,天然执行了这个watcher, 组件从新render。github
在 vue的仓库中vue/src/core/instance/lifecycle.js
中mountComponent
方法中,能看到挂载组件时是会生成一个watcher
的:vue-router
export function mountComponent( vm: Component, el: ?Element, hydrating?: boolean ) { ... let updateComponent updateComponent = () => { vm._update(vm._render(), hydrating) } new Watcher(vm, updateComponent, noop, { before() { ... } }) ... return vm }
Object.defineProperty(Vue.prototype, '$router', { get () { return this._routerRoot._router } }) Object.defineProperty(Vue.prototype, '$route', { get () { return this._routerRoot._route } })
// 替换现有router的routes router.matcher = new VueRouter({ routes: newRoutes }).matcher
router.matcher是比较核心的一个属性。对外提供两个方法match(负责route匹配), addRoutes(动态添加路由)。框架
具体缘由:在作路径切换transitionTo
方法中,首先就会使用const route = this.router.match(location, this.current)
来匹配route, 其实内部会使用matcher来作匹配。修改了matcher即新的routes生效。函数
match ( raw: RawLocation, current?: Route, redirectedFrom?: Location ): Route { // 这里使用matcher的match方法来作匹配 return this.matcher.match(raw, current, redirectedFrom) }
对router.matcher属性作修改,即新的routes就会替换老的routes, 其实就是replaceRoutes()
的含义(可是官方没有提供这个API)。oop
export type Matcher = { match: (raw: RawLocation, current?: Route, redirectedFrom?: Location) => Route; addRoutes: (routes: Array<RouteConfig>) => void; };
<router-view> 组件是一个functional 组件,渲染路径匹配到的视图组件。<router-view> 渲染的组件还能够内嵌本身的 <router-view>,根据嵌套路径,渲染嵌套组件。this
<transition> <keep-alive> <router-view></router-view> </keep-alive> </transition>
初始化url
路由监听
路由变化处理
两种方式触发路由变化
路由变化具体处理过程
router的辅助API
https://cnodejs.org/topic/58d... 这篇文章讲大框架,和几个重点问题 【推荐阅读】
https://zhuanlan.zhihu.com/p/... 这篇文章讲的也比较详细,最好的是提供了本身造的vue-router的简易版轮子,更方便你们理解,这个轮子很好。 【推荐阅读轮子这一部分】
https://ustbhuangyi.github.io... 这个更加详细,可是废话太多,有点看不清重点,【随缘阅读】