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... 這個更加詳細,可是廢話太多,有點看不清重點,【隨緣閱讀】