【vue-進階】之vue-router源碼分析

這是一篇集合了從如何查看 vue-router源碼(v3.1.3),到 vue-router源碼解析,以及擴展了相關涉及的知識點,科普了完整的導航解析流程圖,一時讀不完,建議收藏。

如何查看vue-router源碼

查看源碼的方法有很多,下面是我自己讀vue-router源碼的兩種方法,大家都是怎么查看源碼的,歡迎在評論區留言。

查看vue-router源碼 方法一:
  1. 下載好 vue-router 源碼,安裝好依賴。
  2. 找到 build/config.js 修改 module.exports,只保留 es,其它的注釋。
module.exports = [
    {
        file: resolve('dist/vue-router.esm.js'),
        format: 'es'
    }
].map(genConfig)
  1. 在根目錄下創建一個 auto-running.js 文件,用于監聽src文件的改變的腳本,監聽到vue-router 源碼變更就從新構建vue-router執行 node auto-running.js 命令。auto-running.js的代碼如下:
const { exec } = require('child_process')
const fs = require('fs')

let building = false

fs.watch('./src', {
  recursive: true
}, (event, filename) => {
  if (building) {
    return
  } else {
    building = true
    console.log('start: building ...')
    exec('npm run build', (err, stdout, stderr) => {
      if (err) {
        console.log(err)
      } else {
        console.log('end: building: ', stdout)
      }
      building = false
    })
  }
})

4.執行 npm run dev命令,將 vue-router 跑起來

查看vue-router源碼方法二:

一般項目中的node_modules的vue-router的src不全 不方便查看源碼;

所以需要自己下載一個vue-router的完整版,看到哪里不清楚了,就去vue-router的node_modules的 dist>vue-router.esm.js 文件里去打debugger。

為什么要在vue-router.esm.js文件里打點而不是vue-router.js;是因為webpack在進行打包的時候用的是esm.js文件。

為什么要在esm.js文件中打debugger

在vue-router源碼的 dist/目錄,有很多不同的構建版本。

版本 UMD Common JS ES Module(基于構建工具使用) ES Modules(直接用于瀏覽器)
完整版 vue-router.js vue-router.common.js vue-router.esm.js vue-router.esm.browser.js
完整版(生產環境) vue-router.min.js vue-router.esm.browser.min.js
  • 完整版:同時包含編譯器和運行時的版本
  • UMD:UMD版本可以通過 <script> 標簽直接用在瀏覽器中。
  • CommonJS: CommonJS版本用來配合老的打包工具比如webpack1。
  • ES Module: 有兩個ES Modules構建文件:
    1. 為打包工具提供的ESM,ESM被設計為可以被靜態分析,打包工具可以利用這一點來進行“tree-shaking”。
    2. 為瀏覽器提供的ESM,在現代瀏覽器中通過 <script type="module"> 直接導入

現在清楚為什么要在esm.js文件中打點,因為esm文件為打包工具提供的esm,打包工具可以進行“tree-shaking”。

vue-router項目src的目錄樹

.
├── components
│   ├── link.js
│   └── view.js
├── create-matcher.js
├── create-route-map.js
├── history
│   ├── abstract.js
│   ├── base.js
│   ├── errors.js
│   ├── hash.js
│   └── html5.js
├── index.js
├── install.js
└── util
    ├── async.js
    ├── dom.js
    ├── location.js
    ├── misc.js
    ├── params.js
    ├── path.js
    ├── push-state.js
    ├── query.js
    ├── resolve-components.js
    ├── route.js
    ├── scroll.js
    ├── state-key.js
    └── warn.js

vue-router的使用

vue-router 是vue的插件,其使用方式跟普通的vue插件類似都需要按照、插件和注冊。
vue-router的基礎使用在 vue-router 項目中 examples/basic,注意代碼注釋。

// 0.在模塊化工程中使用,導入Vue和VueRouter
import Vue from 'vue'
import VueRouter from 'vue-router'


// 1. 插件的使用,必須通過Vue.use()明確地安裝路由
// 在全局注入了兩個組件 <router-view> 和 <router-link>,
// 并且在全局注入 $router 和 $route,
// 可以在實例化的所有的vue組件中使用 $router路由實例、$route當前路由對象
Vue.use(VueRouter)

// 2. 定義路由組件
const Home = { template: '<div>home</div>' }
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }
const Unicode = { template: '<div>unicode</div>' }

// 3. 創建路由實例 實例接收了一個對象參數,
// 參數mode:路由模式,
// 參數routes路由配置 將組件映射到路由
const router = new VueRouter({
  mode: 'history',
  routes: [
    { path: '/', component: Home },
    { path: '/foo', component: Foo },
    { path: '/bar', component: Bar },
    { path: '/é', component: Unicode }
  ]
})

// 4. 創建和掛載根實例
// 通過router參數注入到vue里 讓整個應用都有路由參數
// 在應用中通過組件<router-view>,進行路由切換
// template里有寫特殊用法 我們晚點討論
new Vue({
  router,
  data: () => ({ n: 0 }),
  template: `
    <div id="app">
      <h1>Basic</h1>
      <ul>
        <!-- 使用 router-link 創建a標簽來定義導航鏈接. to屬性為執行鏈接-->
        <li><router-link to="/">/</router-link></li>
        <li><router-link to="/foo">/foo</router-link></li>
        <li><router-link to="/bar">/bar</router-link></li>
        <!-- 通過tag屬性可以指定渲染的標簽 這里是li標簽  event自定義了事件-->
        <router-link tag="li" to="/bar" :event="['mousedown', 'touchstart']">
          <a>/bar</a>
        </router-link>
        <li><router-link to="/é">/é</router-link></li>
        <li><router-link to="/é?t=%25?">/é?t=%?</router-link></li>
        <li><router-link to="/é#%25?">/é#%25?</router-link></li>
        <!-- router-link可以作為slot,插入內容,如果內容中有a標簽,會把to屬性的鏈接給內部的a標簽 -->
        <router-link to="/foo" v-slot="props">
          <li :class="[props.isActive && 'active', props.isExactActive && 'exact-active']">
            <a :href="props.href" @click="props.navigate">{{ props.route.path }} (with v-slot).</a>
          </li>
        </router-link>
      </ul>
      <button id="navigate-btn" @click="navigateAndIncrement">On Success</button>
      <pre id="counter">{{ n }}</pre>
      <pre id="query-t">{{ $route.query.t }}</pre>
      <pre id="hash">{{ $route.hash }}</pre>
      
      <!-- 路由匹配到的組件將渲染在這里 -->
      <router-view class="view"></router-view>
    </div>
  `,

  methods: {
    navigateAndIncrement () {
      const increment = () => this.n++
      // 路由注冊后,我們可以在Vue實例內部通過 this.$router 訪問路由實例,
      // 通過 this.$route 訪問當前路由
      if (this.$route.path === '/') {
        // this.$router.push 會向history棧添加一個新的記錄
        // <router-link>內部也是調用來 router.push,實現原理相同
        this.$router.push('/foo', increment)
      } else {
        this.$router.push('/', increment)
      }
    }
  }
}).$mount('#app')

使用 this.$router 的原因是并不想用戶在每個獨立需要封裝路由的組件中都導入路由。<router-view> 是最頂層的出口,渲染最高級路由匹配的組件,要在嵌套的出口中渲染組件,需要在 VueRouter 的參數中使用 children 配置。

注入路由和路由實例化都干了點啥

Vue提供了插件注冊機制是,每個插件都需要實現一個靜態的 install方法,當執行 Vue.use 注冊插件的時候,就會執行 install 方法,該方法執行的時候第一個參數強制是 Vue對象。

為什么install的插件方法第一個參數是Vue

Vue插件的策略,編寫插件的時候就不需要inport Vue了,在注冊插件的時候,給插件強制插入一個參數就是 Vue 實例。

vue-router注入的時候時候,install了什么
// 引入install方法
import { install } from './install'

export default class VueRouter {
    // 在VueRouter類中定義install靜態方法
    static install: () => void;
}

// 給VueRouter.install復制
VueRouter.install = install

// 以鏈接的形式引入vue-router插件 直接注冊vue-router
if (inBrowser && window.Vue) {
  window.Vue.use(VueRouter)
}

vue-router源碼中,入口文件是 src/index.js,其中定義了 VueRouter 類,在VueRouter類中定義靜態方法 install,它定義在 src/install.js中。

src/install.js文件中路由注冊的時候install了什么
import View from './components/view'
import Link from './components/link'

// 導出Vue實例
export let _Vue

// install 方法 當Vue.use(vueRouter)時 相當于 Vue.use(vueRouter.install())
export function install (Vue) {
  // vue-router注冊處理 只注冊一次即可
  if (install.installed && _Vue === Vue) return
  install.installed = true

  // 保存Vue實例,方便其它插件文件使用
  _Vue = Vue

  const isDef = v => v !== undefined

  const registerInstance = (vm, callVal) => {
    let i = vm.$options._parentVnode
    if (isDef(i) && isDef(i = i.data) && isDef(i = i.registerRouteInstance)) {
      i(vm, callVal)
    }
  }

  /**
   * 注冊vue-router的時候,給所有的vue組件混入兩個生命周期beforeCreate、destroyed
   * 在beforeCreated中初始化vue-router,并將_route響應式
   */
  Vue.mixin({
    beforeCreate () {
      // 如果vue的實例的自定義屬性有router的話,把vue實例掛在到vue實例的_routerRoot上
      if (isDef(this.$options.router)) {
        // 給大佬遞貓 把自己遞大佬
        this._routerRoot = this

        // 把VueRouter實例掛載到_router上
        this._router = this.$options.router

        // 初始化vue-router,init為核心方法,init定義在src/index.js中,晚些再看
        this._router.init(this)

        // 將當前的route對象 隱式掛到當前組件的data上,使其成為響應式變量。
        Vue.util.defineReactive(this, '_route', this._router.history.current)
      } else {
        // 找爸爸,自身沒有_routerRoot,找其父組件的_routerRoot
        this._routerRoot = (this.$parent && this.$parent._routerRoot) || this
      }
      registerInstance(this, this)
    },
    destroyed () {
      registerInstance(this)
    }
  })

  /**
   * 給Vue添加實例對象$router和$route
   * $router為router實例
   * $route為當前的route
   */
  Object.defineProperty(Vue.prototype, '$router', {
    get () { return this._routerRoot._router }
  })

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

  /**
   * 注入兩個全局組件
   * <router-view>
   * <router-link>
   */
  Vue.component('RouterView', View)
  Vue.component('RouterLink', Link)

  /**
   * Vue.config 是一個對象,包含了Vue的全局配置
   * 將vue-router的hook進行Vue的合并策略
   */
  const strats = Vue.config.optionMergeStrategies
  // use the same hook merging strategy for route hooks
  strats.beforeRouteEnter = strats.beforeRouteLeave = strats.beforeRouteUpdate = strats.created
}

為了保證 VueRouter 只執行一次,當執行 install 邏輯的時候添加一個標識 installed。用一個全局變量保存Vue,方便VueRouter插件各處對Vue的使用。這個思想就很好,以后自己寫Vue插件的時候就可以存一個全局的 _Vue

VueRouter安裝的核心是通過 mixin,向應用的所有組件混入 beforeCreatedestroyed鉤子函數。在beforeCreate鉤子函數中,定義了私有屬性_routerRoot_router

  • _routerRoot: 將Vue實例賦值給_routerRoot,相當于把Vue跟實例掛載到每個組件的_routerRoot的屬性上,通過 $parent._routerRoot 的方式,讓所有組件都能擁有_routerRoot始終指向根Vue實例。
  • _router:通過 this.$options.router方式,讓每個vue組件都能拿到VueRouter實例

用Vue的defineReactive方法把 _route 變成響應式對象。this._router.init() 初始化了router,init方法在 src/index.js中,init方法很重要,后面介紹。registerInstance 也是后面介紹。

然后給Vue的原型上掛載了兩個對象屬性 $router$route,在應用的所有組件實例上都可以訪問 this.$routerthis.$routethis.$router 是路由實例,對外暴露了像this.$router.pushthis.$router.replace等很多api方法,this.$route包含了當前路由的所有信息。是很有用的兩個方法。

后面通過 Vue.component 方法定義了全局的 <router-link><router-view> 兩個組件。<router-link>類似于a標簽,<router-view> 是路由出口,在 <router-view> 切換路由渲染不同Vue組件。

最后定義了路由守衛的合并策略,采用了Vue的合并策略。

小結

Vue插件需要提供 install 方法,用于插件的注入。VueRouter安裝時會給應用的所有組件注入 beforeCreatedestoryed 鉤子函數。在 beforeCreate 中定義一些私有變量,初始化了路由。全局注冊了兩個組件和兩個api。

那么問題來了,初始化路由都干了啥

VueRouter類定義很多屬性和方法,我們先看看初始化路由方法 init。初始化路由的代碼是 this._router.init(this),init接收了Vue實例,下面的app就是Vue實例。注釋寫的很詳細了,這里就不文字敘述了。

init (app: any /* Vue component instance */) {
    // vueRouter可能會實例化多次 apps用于存放多個vueRouter實例
    this.apps.push(app)

    // 保證VueRouter只初始化一次,如果初始化了就終止后續邏輯
    if (this.app) {
      return
    }

    // 將vue實例掛載到vueRouter上,router掛載到Vue實例上,哈 給大佬遞貓
    this.app = app

    // history是vueRouter維護的全局變量,很重要
    const history = this.history

    // 針對不同路由模式做不同的處理 transitionTo是history的核心方法,后面再細看
    if (history instanceof HTML5History) {
      history.transitionTo(history.getCurrentLocation())
    } else if (history instanceof HashHistory) {
      const setupHashListener = () => {
        history.setupListeners()
      }
      history.transitionTo(
        history.getCurrentLocation(),
        setupHashListener,
        setupHashListener
      )
    }

    // 路由全局監聽,維護當前的route
    // 因為_route在install執行時定義為響應式屬性,
    // 當route變更時_route更新,后面的視圖更新渲染就是依賴于_route
    history.listen(route => {
      this.apps.forEach((app) => {
        app._route = route
      })
    })
  }
history

接下來看看 new VueRouter 時constructor做了什么。

constructor (options: RouterOptions = {}) {
    this.app = null
    this.apps = []
    this.options = options
    this.beforeHooks = []
    this.resolveHooks = []
    this.afterHooks = []
    // 創建 matcher 匹配函數,createMatcher函數返回一個對象 {match, addRoutes} 很重要
    this.matcher = createMatcher(options.routes || [], this)

    // 默認hash模式
    let mode = options.mode || 'hash'

    // h5的history有兼容性 對history做降級處理
    this.fallback = mode === 'history' && !supportsPushState && options.fallback !== false
    if (this.fallback) {
      mode = 'hash'
    }
    if (!inBrowser) {
      mode = 'abstract'
    }
    this.mode = mode

    // 不同的mode,實例化不同的History類, 后面的this.history就是History的實例
    switch (mode) {
      case 'history':
        this.history = new HTML5History(this, options.base)
        break
      case 'hash':
        this.history = new HashHistory(this, options.base, this.fallback)
        break
      case 'abstract':
        this.history = new AbstractHistory(this, options.base)
        break
      default:
        if (process.env.NODE_ENV !== 'production') {
          assert(false, `invalid mode: ${mode}`)
        }
    }
}

constructoroptions 是實例化路由是的傳參,通常是一個對象 {routes, mode: 'history'}, routes是必傳參數,mode默認是hash模式。vueRouter還定義了哪些東西呢。

...

match (
    raw: RawLocation,
    current?: Route,
    redirectedFrom?: Location
  ): Route {
    return this.matcher.match(raw, current, redirectedFrom)
}

// 獲取當前的路由
get currentRoute (): ?Route {
    return this.history && this.history.current
}
  
init(options) { ... }

beforeEach(fn) { ... }
beforeResolve(fn) { ... }
afterEach(fn) { ... }
onReady(cb) { ... }

push(location) { ... }
replace(location) { ... }
back() { ... }
go(n) { ... }
forward() { ... }

// 獲取匹配到的路由組件
getMatchedComponents (to?: RawLocation | Route): Array<any> {
    const route: any = to
      ? to.matched
        ? to
        : this.resolve(to).route
      : this.currentRoute
    if (!route) {
      return []
    }
    return [].concat.apply([], route.matched.map(m => {
      return Object.keys(m.components).map(key => {
        return m.components[key]
      })
    }))
}

addRoutes (routes: Array<RouteConfig>) {
    this.matcher.addRoutes(routes)
    if (this.history.current !== START) {
      this.history.transitionTo(this.history.getCurrentLocation())
    }
}

在實例化的時候,vueRouter仿照history定義了一些api:pushreplacebackgoforward,還定義了路由匹配器、添加router動態更新方法等。

小結

install的時候先執行init方法,然后實例化vueRouter的時候定義一些屬性和方法。init執行的時候通過 history.transitionTo 做路由過渡。matcher 路由匹配器是后面路由切換,路由和組件匹配的核心函數。所以...en

matcher了解一下吧

在VueRouter對象中有以下代碼:

// 路由匹配器,createMatcher函數返回一個對象 {match, addRoutes}
this.matcher = createMatcher(options.routes || [], this)

...

match (
    raw: RawLocation,
    current?: Route,
    redirectedFrom?: Location
): Route {
    return this.matcher.match(raw, current, redirectedFrom)
}

...

const route = this.match(location, current)

我們可以觀察到 route 對象通過 this.match() 獲取,match 又是通過 this.matcher.match(),而 this.matcher 是通過 createMatcher 函數處理。接下來我們去看看createMatcher函數的實現。

createMatcher

createMatcher 相關的實現都在 src/create-matcher.js中。

/**
 * 創建createMatcher 
 * @param {*} routes 路由配置
 * @param {*} router 路由實例
 * 
 * 返回一個對象 {
 *  match, // 當前路由的match 
 *  addRoutes // 更新路由配置
 * }
 */
export function createMatcher (
  routes: Array<RouteConfig>,
  router: VueRouter
): Matcher {
  const { pathList, pathMap, nameMap } = createRouteMap(routes)

  function addRoutes (routes) {
    createRouteMap(routes, pathList, pathMap, nameMap)
  }

  function match (
    raw: RawLocation,
    currentRoute?: Route,
    redirectedFrom?: Location
  ): Route {

  ...

  return {
    match,
    addRoutes
  }
}

createMatcher 接收2個參數,routes 是用戶定義的路由配置,routernew VueRouter 返回的實例。routes 是一個定義了路由配置的數組,通過 createRouteMap 函數處理為 pathList, pathMap, nameMap,返回了一個對象 {match, addRoutes} 。也就是說 matcher 是一個對象,它對外暴露了 matchaddRoutes 方法。

一會我們先了解下 pathList, pathMap, nameMap分別是什么,稍后在來看createRouteMap的實現。

  • pathList:路由路徑數組,存儲所有的path
  • pathMap:路由路徑與路由記錄的映射表,表示一個path到RouteRecord的映射關系
  • nameMap:路由名稱與路由記錄的映射表,表示name到RouteRecord的映射關系
RouteRecord

那么路由記錄是什么樣子的?

const record: RouteRecord = {
    path: normalizedPath,
    regex: compileRouteRegex(normalizedPath, pathToRegexpOptions),
    components: route.components || { default: route.component },
    instances: {},
    name,
    parent,
    matchAs,
    redirect: route.redirect,
    beforeEnter: route.beforeEnter,
    meta: route.meta || {},
    props:
      route.props == null
        ? {}
        : route.components
          ? route.props
          : { default: route.props }
}

RouteRecord 是一個對象,包含了一條路由的所有信息: 路徑、路由正則、路徑對應的組件數組、組件實例、路由名稱等等。

router對象
createRouteMap

createRouteMap 函數的實現在 src/create-route-map中:

/**
 * 
 * @param {*} routes 用戶路由配置
 * @param {*} oldPathList 老pathList
 * @param {*} oldPathMap 老pathMap
 * @param {*} oldNameMap 老nameMap
 */
export function createRouteMap (
  routes: Array<RouteConfig>,
  oldPathList?: Array<string>,
  oldPathMap?: Dictionary<RouteRecord>,
  oldNameMap?: Dictionary<RouteRecord>
): {
  pathList: Array<string>,
  pathMap: Dictionary<RouteRecord>,
  nameMap: Dictionary<RouteRecord>
} {
  // pathList被用于控制路由匹配優先級
  const pathList: Array<string> = oldPathList || []
  // 路徑路由映射表
  const pathMap: Dictionary<RouteRecord> = oldPathMap || Object.create(null)
  // 路由名稱路由映射表
  const nameMap: Dictionary<RouteRecord> = oldNameMap || Object.create(null)

  routes.forEach(route => {
    addRouteRecord(pathList, pathMap, nameMap, route)
  })

  // 確保通配符路由總是在最后
  for (let i = 0, l = pathList.length; i < l; i++) {
    if (pathList[i] === '*') {
      pathList.push(pathList.splice(i, 1)[0])
      l--
      i--
    }
  }

  ...

  return {
    pathList,
    pathMap,
    nameMap
  }
}

createRouteMap 函數主要是把用戶的路由匹配轉換成一張路由映射表,后面路由切換就是依據這幾個映射表。routes 為每一個 route 執行 addRouteRecord 方法生成一條記錄,記錄在上面展示過了,我們來看看是如何生成一條記錄的。

addRouteRecord
function addRouteRecord (
  pathList: Array<string>,
  pathMap: Dictionary<RouteRecord>,
  nameMap: Dictionary<RouteRecord>,
  route: RouteConfig,
  parent?: RouteRecord,
  matchAs?: string
) {

  //...
  // 先創建一條路由記錄
  const record: RouteRecord = { ... }

  // 如果該路由記錄 嵌套路由的話 就循環遍歷解析嵌套路由
  if (route.children) {
    // ...
    // 通過遞歸的方式來深度遍歷,并把當前的record作為parent傳入
    route.children.forEach(child => {
      const childMatchAs = matchAs
        ? cleanPath(`${matchAs}/${child.path}`)
        : undefined
      addRouteRecord(pathList, pathMap, nameMap, child, record, childMatchAs)
    })
  }

  // 如果有多個相同的路徑,只有第一個起作用,后面的會被忽略
  // 對解析好的路由進行記錄,為pathList、pathMap添加一條記錄
  if (!pathMap[record.path]) {
    pathList.push(record.path)
    pathMap[record.path] = record
  }
  // ...
}

addRouteRecord 函數,先創建一條路由記錄對象。如果當前的路由記錄有嵌套路由的話,就循環遍歷繼續創建路由記錄,并按照路徑和路由名稱進行路由記錄映射。這樣所有的路由記錄都被記錄了。整個RouteRecord就是一個樹型結構,其中 parent 表示父的 RouteRecord

if (name) {
  if (!nameMap[name]) {
    nameMap[name] = record
  }
  // ...
}

如果我們在路由配置中設置了 name,會給 nameMap添加一條記錄。createRouteMap 方法執行后,我們就可以得到路由的完整記錄,并且得到path、name對應的路由映射。通過pathname 能在 pathMapnameMap快速查到對應的 RouteRecord

export function createMatcher (
  routes: Array<RouteConfig>,
  router: VueRouter
): Matcher {
  //...
  return {
    match,
    addRoutes
  }
}

還記得 createMatcher 的返回值中有個 match,接下里我們看 match的實現。

match
/**
  * 
  * @param {*} raw 是RawLocation類型 是個url字符串或者RawLocation對象
  * @param {*} currentRoute 當前的route
  * @param {*} redirectedFrom 重定向 (不是重要,可忽略)
  */
function match (
  raw: RawLocation,
  currentRoute?: Route,
  redirectedFrom?: Location
): Route {

    // location 是一個對象類似于
    // {"_normalized":true,"path":"/","query":{},"hash":""}
    const location = normalizeLocation(raw, currentRoute, false, router)
    const { name } = location

    // 如果有路由名稱 就進行nameMap映射 
    // 獲取到路由記錄 處理路由params 返回一個_createRoute處理的東西
    if (name) {
      const record = nameMap[name]
      if (process.env.NODE_ENV !== 'production') {
        warn(record, `Route with name '${name}' does not exist`)
      }
      if (!record) return _createRoute(null, location)
      const paramNames = record.regex.keys
        .filter(key => !key.optional)
        .map(key => key.name)

      if (typeof location.params !== 'object') {
        location.params = {}
      }

      if (currentRoute && typeof currentRoute.params === 'object') {
        for (const key in currentRoute.params) {
          if (!(key in location.params) && paramNames.indexOf(key) > -1) {
            location.params[key] = currentRoute.params[key]
          }
        }
      }

      location.path = fillParams(record.path, location.params, `named route "${name}"`)
      return _createRoute(record, location, redirectedFrom)
    
    // 如果路由配置了 path,到pathList和PathMap里匹配到路由記錄 
    // 如果符合matchRoute 就返回_createRoute處理的東西
    } else if (location.path) {
      location.params = {}
      for (let i = 0; i < pathList.length; i++) {
        const path = pathList[i]
        const record = pathMap[path]
        if (matchRoute(record.regex, location.path, location.params)) {
          return _createRoute(record, location, redirectedFrom)
        }
      }
    }
    // 通過_createRoute返回一個東西
    return _createRoute(null, location)
}

match 方法接收路徑、但前路由、重定向,主要是根據傳入的rawcurrentRoute處理,返回的是 _createRoute()。來看看 _createRoute返回了什么,就知道 match返回了什么了。

function _createRoute (
    record: ?RouteRecord,
    location: Location,
    redirectedFrom?: Location
  ): Route {
    if (record && record.redirect) {
      return redirect(record, redirectedFrom || location)
    }
    if (record && record.matchAs) {
      return alias(record, location, record.matchAs)
    }
    return createRoute(record, location, redirectedFrom, router)
}

_createRoute 函數根據有是否有路由重定向、路由重命名做不同的處理。其中redirect 函數和 alias 函數最后還是調用了 _createRoute,最后都是調用了 createRoute。而來自于 util/route

/**
 * 
 * @param {*} record 一般為null
 * @param {*} location 路由對象
 * @param {*} redirectedFrom 重定向
 * @param {*} router vueRouter實例
 */
export function createRoute (
  record: ?RouteRecord,
  location: Location,
  redirectedFrom?: ?Location,
  router?: VueRouter
): Route {
  const stringifyQuery = router && router.options.stringifyQuery

  let query: any = location.query || {}
  try {
    query = clone(query)
  } catch (e) {}

  const route: Route = {
    name: location.name || (record && record.name),
    meta: (record && record.meta) || {},
    path: location.path || '/',
    hash: location.hash || '',
    query,
    params: location.params || {},
    fullPath: getFullPath(location, stringifyQuery),
    matched: record ? formatMatch(record) : []
  }
  if (redirectedFrom) {
    route.redirectedFrom = getFullPath(redirectedFrom, stringifyQuery)
  }
  // 凍結route 一旦創建不可改變
  return Object.freeze(route)
}

createRoute 可以根據 recordlocation 創建出來最終返回 Route 對象,并且外部不可以修改,只能訪問。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 都push到一個數組中,最終飯后就是一個 record 數組,這個 matched 為后面的渲染組件提供了重要的作用。

小結

matcher的主流程就是通過createMatcher 返回一個對象 {match, addRoutes}, addRoutes 是動態添加路由用的,平時使用頻率比較低,match 很重要,返回一個路由對象,這個路由對象上記錄當前路由的基本信息,以及路徑匹配的路由記錄,為路徑切換、組件渲染提供了依據。那路徑是怎么切換的,又是怎么渲染組件的呢。喝杯誰,我們繼續繼續往下看。

路徑切換

還記得 vue-router 初始化的時候,調用了 init 方法,在 init方法里針對不同的路由模式最后都調用了 history.transitionTo,進行路由初始化匹配。包括 history.pushhistory.replace的底層都是調用了它。它就是路由切換的方法,很重要。它的實現在 src/history/base.js,我們來看看。

transitionTo (
    location: RawLocation,
    onComplete?: Function,
    onAbort?: Function
) {
    // 調用 match方法得到匹配的 route對象
    const route = this.router.match(location, this.current)
    
    // 過渡處理
    this.confirmTransition(
        route,
        () => {
            // 更新當前的 route 對象
            this.updateRoute(route)
            onComplete && onComplete(route)
            
            // 更新url地址 hash模式更新hash值 history模式通過pushState/replaceState來更新
            this.ensureURL()
    
            // fire ready cbs once
            if (!this.ready) {
                this.ready = true
                this.readyCbs.forEach(cb => {
                cb(route)
                })
            }
        },
        err => {
            if (onAbort) {
                onAbort(err)
            }
            if (err && !this.ready) {
                this.ready = true
                this.readyErrorCbs.forEach(cb => {
                cb(err)
                })
            }
        }
    )
}

transitionTo 可以接收三個參數 locationonCompleteonAbort,分別是目標路徑、路經切換成功的回調、路徑切換失敗的回調。transitionTo 函數主要做了兩件事:首先根據目標路徑 location 和當前的路由對象通過 this.router.match方法去匹配到目標 route 對象。route是這個樣子的:

const route = {
    fullPath: "/detail/394"
    hash: ""
    matched: [{…}]
    meta: {title: "工單詳情"}
    name: "detail"
    params: {id: "394"}
    path: "/detail/394"
    query: {}
}

一個包含了目標路由基本信息的對象。然后執行 confirmTransition方法進行真正的路由切換。因為有一些異步組件,所以回有一些異步操作。具體的實現:

confirmTransition (route: Route, onComplete: Function, onAbort?: Function) {
    const current = this.current
    const abort = err => {
      // ...
      onAbort && onAbort(err)
    }
    
    // 如果當前路由和之前路由相同 確認url 直接return
    if (
      isSameRoute(route, current) &&
      route.matched.length === current.matched.length
    ) {
      this.ensureURL()
      return abort(new NavigationDuplicated(route))
    }

    // 通過異步隊列來交叉對比當前路由的路由記錄和現在的這個路由的路由記錄 
    // 為了能準確得到父子路由更新的情況下可以確切的知道 哪些組件需要更新 哪些不需要更新
    const { updated, deactivated, activated } = resolveQueue(
      this.current.matched,
      route.matched
    )

    // 在異步隊列中執行響應的勾子函數
    // 通過 queue 這個數組保存相應的路由鉤子函數
    const queue: Array<?NavigationGuard> = [].concat(
      // leave 的勾子
      extractLeaveGuards(deactivated),
      // 全局的 before 的勾子
      this.router.beforeHooks,
      // in-component update hooks
      extractUpdateHooks(updated),
      // 將要更新的路由的 beforeEnter勾子
      activated.map(m => m.beforeEnter),
      // 異步組件
      resolveAsyncComponents(activated)
    )

    this.pending = route

    // 隊列執行的iterator函數 
    const iterator = (hook: NavigationGuard, next) => {
      if (this.pending !== route) {
        return abort()
      }
      try {
        hook(route, current, (to: any) => {
          if (to === false || isError(to)) {
            // next(false) -> abort navigation, ensure current URL
            this.ensureURL(true)
            abort(to)
          } else if (
            typeof to === 'string' ||
            (typeof to === 'object' &&
              (typeof to.path === 'string' || typeof to.name === 'string'))
          ) {
            // next('/') or next({ path: '/' }) -> redirect
            abort()
            if (typeof to === 'object' && to.replace) {
              this.replace(to)
            } else {
              this.push(to)
            }
          } else {
            // confirm transition and pass on the value
            // 如果有導航鉤子,就需要調用next(),否則回調不執行,導航將無法繼續
            next(to)
          }
        })
      } catch (e) {
        abort(e)
      }
    }

    // runQueue 執行隊列 以一種遞歸回調的方式來啟動異步函數隊列的執行
    runQueue(queue, iterator, () => {
      const postEnterCbs = []
      const isValid = () => this.current === route

      // 組件內的鉤子
      const enterGuards = extractEnterGuards(activated, postEnterCbs, isValid)
      const queue = enterGuards.concat(this.router.resolveHooks)
      // 在上次的隊列執行完成后再執行組件內的鉤子
      // 因為需要等異步組件以及是否OK的情況下才能執行
      runQueue(queue, iterator, () => {
        // 確保期間還是當前路由
        if (this.pending !== route) {
          return abort()
        }
        this.pending = null
        onComplete(route)
        if (this.router.app) {
          this.router.app.$nextTick(() => {
            postEnterCbs.forEach(cb => {
              cb()
            })
          })
        }
      })
    })
}

查看目標路由 route 和當前前路由 current 是否相同,如果相同就調用 this.ensureUrlabort

// ensureUrl todo

接下來執行了 resolveQueue函數,這個函數要好好看看:

function resolveQueue (
  current: Array<RouteRecord>,
  next: Array<RouteRecord>
): {
  updated: Array<RouteRecord>,
  activated: Array<RouteRecord>,
  deactivated: Array<RouteRecord>
} {
  let i
  const max = Math.max(current.length, next.length)
  for (i = 0; i < max; i++) {
    if (current[i] !== next[i]) {
      break
    }
  }
  return {
    updated: next.slice(0, i),
    activated: next.slice(i),
    deactivated: current.slice(i)
  }
}

resolveQueue函數接收兩個參數:當前路由的 matched 和目標路由的 matchedmatched 是個數組。通過遍歷對比兩遍的路由記錄數組,當有一個路由記錄不一樣的時候就記錄這個位置,并終止遍歷。對于 next 從0到i和current都是一樣的,從i口開始不同,next 從i之后為 activated部分,current從i之后為 deactivated部分,相同部分為 updated,由 resolveQueue 處理之后就能得到路由變更需要更改的部分。緊接著就可以根據路由的變更執行一系列的鉤子函數。完整的導航解析流程有12步,后面會出一篇vue-router路由切換的內部實現文章。盡情期待

路由改變路由組件是如何渲染的

路由的變更之后,路由組件隨之的渲染都是在 <router-view> 組件,它的定義在 src/components/view.js中。

router-view 組件
export default {
  name: 'RouterView',
  functional: true,
  props: {
    name: {
      type: String,
      default: 'default'
    }
  },
  render (_, { props, children, parent, data }) {
    data.routerView = true
    const h = parent.$createElement
    const name = props.name
    const route = parent.$route
    const cache = parent._routerViewCache || (parent._routerViewCache = {})
    let depth = 0
    let inactive = false
    while (parent && parent._routerRoot !== parent) {
      if (parent.$vnode && parent.$vnode.data.routerView) {
        depth++
      }
      if (parent._inactive) {
        inactive = true
      }
      parent = parent.$parent
    }
    data.routerViewDepth = depth
    if (inactive) {
      return h(cache[name], data, children)
    }
    const matched = route.matched[depth]
    if (!matched) {
      cache[name] = null
      return h()
    }
    const component = cache[name] = matched.components[name]
    data.registerRouteInstance = (vm, val) => {     
      const current = matched.instances[name]
      if (
        (val && current !== vm) ||
        (!val && current === vm)
      ) {
        matched.instances[name] = val
      }
    }
    ;(data.hook || (data.hook = {})).prepatch = (_, vnode) => {
      matched.instances[name] = vnode.componentInstance
    }
    let propsToPass = data.props = resolveProps(route, matched.props && matched.props[name])
    if (propsToPass) {
      propsToPass = data.props = extend({}, propsToPass)
      const attrs = data.attrs = data.attrs || {}
      for (const key in propsToPass) {
        if (!component.props || !(key in component.props)) {
          attrs[key] = propsToPass[key]
          delete propsToPass[key]
        }
      }
    }
    return h(component, data, children)
  }
}

<router-view>是一個渲染函數,它的渲染是用了Vue的 render 函數,它接收兩個參數,第一個是Vue實例,第二個是一個context,通過對象解析的方式可以拿到 props、children、parent、data,供創建 <router-view> 使用。

router-link 組件

支持用戶在具有路由功能的組件里使用,通過使用 to 屬性指定目標地址,默認渲染成 <a>標簽,支持通過 tag 自定義標簽和插槽。

export default {
  name: 'RouterLink',
  props: {
    to: {
      type: toTypes,
      required: true
    },
    tag: {
      type: String,
      default: 'a'
    },
    exact: Boolean,
    append: Boolean,
    replace: Boolean,
    activeClass: String,
    exactActiveClass: String,
    event: {
      type: eventTypes,
      default: 'click'
    }
  },
  render (h: Function) {
    const router = this.$router
    const current = this.$route
    const { location, route, href } = router.resolve(this.to, current, this.append)
    const classes = {}
    const globalActiveClass = router.options.linkActiveClass
    const globalExactActiveClass = router.options.linkExactActiveClass
    const activeClassFallback = globalActiveClass == null
            ? 'router-link-active'
            : globalActiveClass
    const exactActiveClassFallback = globalExactActiveClass == null
            ? 'router-link-exact-active'
            : globalExactActiveClass
    const activeClass = this.activeClass == null
            ? activeClassFallback
            : this.activeClass
    const exactActiveClass = this.exactActiveClass == null
            ? exactActiveClassFallback
            : this.exactActiveClass
    const compareTarget = location.path
      ? createRoute(null, location, null, router)
      : route
    classes[exactActiveClass] = isSameRoute(current, compareTarget)
    classes[activeClass] = this.exact
      ? classes[exactActiveClass]
      : isIncludedRoute(current, compareTarget)
    const handler = e => {
      if (guardEvent(e)) {
        if (this.replace) {
          router.replace(location)
        } else {
          router.push(location)
        }
      }
    }
    const on = { click: guardEvent }
    if (Array.isArray(this.event)) {
      this.event.forEach(e => { on[e] = handler })
    } else {
      on[this.event] = handler
    }
    const data: any = {
      class: classes
    }
    if (this.tag === 'a') {
      data.on = on
      data.attrs = { href }
    } else {
      const a = findAnchor(this.$slots.default)
      if (a) {
        a.isStatic = false
        const extend = _Vue.util.extend
        const aData = a.data = extend({}, a.data)
        aData.on = on
        const aAttrs = a.data.attrs = extend({}, a.data.attrs)
        aAttrs.href = href
      } else {
        data.on = on
      }
    }
    return h(this.tag, data, this.$slots.default)
  }
}

<router-link>的特點:

  • history 模式和 hash 模式的標簽一致,針對不支持 history的模式會自動降級為 hash 模式。
  • 可進行路由守衛,不從新加載頁面

<router-link> 的實現也是基于 render 函數。內部實現也是通過 history.push()history.replace() 實現的。

路徑變化是路由中最重要的功能:路由始終會維護當前的線路,;欲嘔切換的時候會把當前線路切換到目標線路,切換過程中會執行一些列的導航守衛鉤子函數,會更改url, 渲染對應的組件,切換完畢后會把目標線路更新替換為當前線路,作為下一次路徑切換的依據。

知識補充

hash模式和history模式的區別

vue-router 默認是hash模式,使用hash模式時,變更URL,頁面不會重新加載,這種模式從ie6就有了,是一種很穩定的路由模式。但是hash的URL上有個 # 號,看上去很丑,后來HTML5出來后,有了history模式。

history 模式通過 history.pushState來完成url的跳轉而無須重新加載頁面,解決了hash模式很臭的問題。但是老瀏覽器不兼容history模式,有些時候我們不得不使用hash模式,來做向下兼容。

history 模式,如果訪問一個不存在的頁面時就會返回 404,為了解決這個問題,需要后臺做配置支持:當URL匹配不到任何靜態資源的時候,返回一個index.html頁面。或者在路由配置里添加一個統一配置的錯誤頁。

const router = new VueRouter({
    mode: 'history',
    routes: [
        {
            path: '*',
            component: NotFoundComponent
        }
    ]
})

Vue Router 的 queryparams 的使用和區別

vue-router中有兩個概念 queryparams,一開始的時候我對它們分不清,相信也有人分不清。這里做個匯總,方便記憶理解。

  • query的使用
// 帶查詢參數,變成 /register?plan=private
router.push({ path: 'register', query: {plan: 'private'}})
  • params的配置和調用
  • 路由配置,使用params傳參數,使用name
{
    path: '/detail/:id',
    name: 'detail',
    component: Detail,
}
  • 調用 this.$router.push 進行params傳參,使用name,前提需要在路由配置里設置過名稱。
this.$router.push({
    name: 'detail',
    params: {
        id: '2019'
    }
})
  • params接收參數
const { id } = this.$route.params

query通常與path使用。query帶查詢參數,params路徑參數。如果提供了path,params會被忽略。

// params 不生效
router.push({ path: '/user', params: { userId }}) // -> /user

導航守衛

導航 表示路由正在發生變化,vue-router 提供的導航守衛主要用來通過跳轉或者取消的方式守衛導航。導航守衛分為三種:全局守衛、單個路由守衛和組件內的守衛。

導航守衛

全局守衛:

  • 全局前置守衛 beforeEach (to, from, next)
  • 全局解析守衛 beforeResolve (to, from, next)
  • 全局后置鉤子 afterEach (to, from)

單個路由守衛:

  • 路由前置守衛 beforeEnter (to, from, next)

組件內的守衛:

  • 渲染組件的對應路由被confirm前 beforeRouterEnter (to, from, next) next可以是函數,因為該守衛不能獲取組件實例,新組件還沒被創建
  • 路由改變,該組件被復用時調用 (to, from, next)
  • 導航離開該組件對應路由時調用 beforeRouteLeave
完整的導航解析流程圖
導航解析流程
  1. 導航被觸發
  2. 在失活的組件里調用離開守衛 beforeRouteLeave
  3. 調用全局的 beforeEach 守衛
  4. 在重用的組件里調用 beforeRouteUpdate 守衛(2.2+)
  5. 在路由配置里調用 beforeEnter
  6. 解析異步路由組件
  7. 在被激活的組件里調用 beforeRouteEnter
  8. 調用全局的 beforeResolve守衛
  9. 導航被確認
  10. 調用全局的 afterEach鉤子
  11. 觸發DOM更新
  12. 用創建好的實例調用 beforeRouterEnter 守衛中傳給next的回調函數
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,238評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,430評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,134評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,893評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,653評論 6 408
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,136評論 1 323
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,212評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,372評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,888評論 1 334
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,738評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,939評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,482評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,179評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,588評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,829評論 1 283
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,610評論 3 391
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,916評論 2 372

推薦閱讀更多精彩內容