vue-router工做原理概述和问题分析

工做原理简要流程图

hashchange
-->
match route
-->
set vm._route
-->
<router-view> render()
-->
render matched component

问题

1. 为何url变动时,router-view组件就能渲染出在routes中定义的与当前path匹配的组件?

  1. root vue实例上定义了一个响应式属性 Vue.util.defineReactive(this, '_route', this._router.history.current)
  2. url变动时,会匹配到最新的route,而且会设置 this._routerRoot._route, 触发setter
  3. router-view组件的render函数中有使用到 parent.$route, 也就是间接的触发了this._routerRoot._routegetter。即进行了依赖搜集。
  4. this._routerRoot._routesetter触发时即会触发router-view渲染watcher, 再次渲染, 而且此时拿到的路由组件也是最新的。

本质上利用了vue的响应式属性,在route属性变动和router-view视图渲染之间创建关系。vue

route变动 => render从新渲染node

2. router-view render中使用到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.jsmountComponent方法中,能看到挂载组件时是会生成一个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
}

3. this.$router, this.$route是怎么挂载每一个vue组件上的?

Object.defineProperty(Vue.prototype, '$router', {
    get () { return this._routerRoot._router }
  })

  Object.defineProperty(Vue.prototype, '$route', {
    get () { return this._routerRoot._route }
  })

4.替换routes的写法(这样写为何有用)

// 替换现有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;
};

5. router-view是什么

<router-view> 组件是一个functional 组件,渲染路径匹配到的视图组件。<router-view> 渲染的组件还能够内嵌本身的 <router-view>,根据嵌套路径,渲染嵌套组件。this

<transition>
  <keep-alive>
    <router-view></router-view>
  </keep-alive>
</transition>

主要流程

  1. 初始化url

    1. 实例化Router, options做为属性,根据mode生成HTML5History实例,或HashHistory实例
    2. 数据劫持,this.router.route =》 this.history.current
    3. 数据劫持,this.history.current.route变化时,自动执行render。
    4. 当即执行一次路由跳转(渲染路由组件)
  2. 路由监听

    1. HashHistory监听hashChange事件,HTML5History监听popstate事件
  3. 路由变化处理

    1. 两种方式触发路由变化

      1. a标签href方法(url先变化,会触发两个history监听的hashChange或popstate事件,而后进入路由变化处理)
      2. 调用router的push, replace, go方法(先进入路由变化处理,而后修改url)
    2. 路由变化具体处理过程

      1. history.transitionTo(根据path匹配到相应的route, 而后调度执行hooks, 而后更新this.current属性,触发视图更新)
      2. history.confirmTransition(调度执行上一个route和下一个route的相关生命周期hooks)
  4. router的辅助API

    1. push(先进行路由变化处理,在更新url,使用history.pushState)
    2. replace() 和push处理方式一致, 只是更新url使用history.replaceState
    3. go 使用history.go方法

参考连接

https://cnodejs.org/topic/58d... 这篇文章讲大框架,和几个重点问题 【推荐阅读】

https://zhuanlan.zhihu.com/p/... 这篇文章讲的也比较详细,最好的是提供了本身造的vue-router的简易版轮子,更方便你们理解,这个轮子很好。 【推荐阅读轮子这一部分】

https://ustbhuangyi.github.io... 这个更加详细,可是废话太多,有点看不清重点,【随缘阅读】