VueRouter源碼分析(1)--主要執行步驟

前言

本文是vue-router 2.x源碼分析的第一篇,主要看vue-router的整體結構!

實例代碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <div id="app">
      <h1>Basic</h1>
      <ul>
        <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>
        <router-link tag="li" to="/bar" :event="['mousedown', 'touchstart']">
          <a>/bar</a>
        </router-link>
      </ul>
      <router-view class="view"></router-view>
    </div>
    <script src='vue.js'></script>
    <script src='vue-router.js'></script>
    <script>
        const Home = { template: '<div>home</div>' }
        const Foo = { template: '<div>foo</div>' }
        const Bar = { template: '<div>bar</div>' }
        //創建router實例
        const router = new VueRouter({
          routes: [
            { path: '/', component: Home },
            { path: '/foo', component: Foo },
            { path: '/bar', component: Bar }
          ]
        })
        //創建vue實例
        new Vue({
          router
        }).$mount('#app')
    </script>
</body>
</html>

1、執行Vue.use(VueRouter)

VueRouter是作為Vue的插件存在的,使用Vue.use(VueRouter)的方式侵入Vue,這個操作在引入vue-router.js時就執行了,Vue.use方法會執行VueRouter的install方法,看下該方法:

function install (Vue) {
    if (install.installed) { return }
    install.installed = true;
    _Vue = Vue;
    //1、將$router和$route定義為Vue.prototype的存取器屬性,以便所有組
    //件都可以訪問到,注意這個get函數,是返回this.$root._router而不是
    //this._router,這是因為在beforeCreate中將_router放在了vue根實例上
    Object.defineProperty(Vue.prototype, '$router', {
        get: function get () { return this.$root._router }
    });
    Object.defineProperty(Vue.prototype, '$route', {
        get: function get () { return this.$root._route }
    });
    var isDef = function (v) { return v !== undefined; };
    var registerInstance = function (vm, callVal) {
        var i = vm.$options._parentVnode;
        if (isDef(i) && isDef(i = i.data) && isDef(i = i.registerRouteInstance)) {
            i(vm, callVal);
        }
    };
    //2、使用mixin構造了一個beforeCreate函數,該函數會在vue實例創建的
    // 時候被調用
    Vue.mixin({
        beforeCreate: function beforeCreate () {
            if (isDef(this.$options.router)) {
                this._router = this.$options.router;
                //執行router的初始化
                this._router.init(this);
                //route定義為響應式以便能在其改變時觸發vue的更新機制
                Vue.util.defineReactive(this, '_route', this._router.history.current);
            }
            registerInstance(this, this);
        },
        destroyed: function destroyed () {
            registerInstance(this);
        }
    });
    // 3、增加vue的默認組件
    Vue.component('router-view', View);
    Vue.component('router-link', Link);
    var strats = Vue.config.optionMergeStrategies;
    // use the same hook merging strategy for route hooks
    strats.beforeRouteEnter = strats.beforeRouteLeave = strats.created;
}

以上三件事執行完,就開始new VueRouter了

2、創建VueRouter實例(new VueRouter(options))

    function VueRouter (options) {
      if ( options === void 0 ) options = {};
      this.app = null;
      this.apps = [];
      this.options = options;
      this.beforeHooks = [];
      this.resolveHooks = [];
      this.afterHooks = [];
      //1、根據傳入的options.routes創建matcher對象
      this.matcher = createMatcher(options.routes || [], this);
      //2、根據傳入的options.mode創建不同的history對象
      var mode = options.mode || 'hash';
      this.fallback = mode === 'history' && !supportsPushState;
      if (this.fallback) {
        mode = 'hash';
      }
      if (!inBrowser) {
        mode = 'abstract';
      }
      this.mode = mode;
      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:
          {
            assert(false, ("invalid mode: " + mode));
          }
      }
    };
  • 先看第一件事,由routes創建matcher
    //routes長這樣:
    routes: [
        { path: '/', component: Home },
        { path: '/foo', component: Foo },
        { path: '/bar', component: Bar }
    ]
    //經過createMatcher處理的matcher長這樣:
    matcher:{
        addRoutes:function addRoutes(routes)
        match:function match( raw, currentRoute, redirectedFrom )
        __proto__:Object
    }
  • 再看第二件事,由mode創建history
    //mode默認值為'hash',故會創建HashHistory實例
    history:{
        base:""
        current:Object
        errorCbs:Array(0)
        pending:null
        ready:false
        readyCbs:Array(0)
        readyErrorCbs:Array(0)
        router:VueRouter
        __proto__:History
    }

最后創建的router實例長這樣:

    router:{
        afterHooks:Array(0)
        app:null
        apps:Array(0)
        beforeHooks:Array(0)
        fallback:false
        history:HashHistory
        matcher:Object
        mode:"hash"
        options:Object
        resolveHooks:Array(0)
        currentRoute:(...)
        __proto__:Object
    }

創建的具體細節以后會分析。這兩件事情做完就開始new Vue(options)了。

3、創建Vue實例(new Vue(options))

創建Vue實例的過程中會調用beforeCreate函數,故在第一節中定義的beforeCreate會得到執行:

    function beforeCreate () {
      if (isDef(this.$options.router)) {
        //1、正式將第二節創建的router實例掛在this._router上,這個this
        //是根實例,相當于子組件中的this.$root,因此在子組件中能通過t
        //his.$router訪問到
        this._router = this.$options.router;
        //2、執行router的初始化
        this._router.init(this);
        //3、將_route定義為響應式以便能在其改變時觸發vue的更新機制
        Vue.util.defineReactive(this, '_route', this._router.history.current);
      }
      //4、注冊組件實例
      registerInstance(this, this);
    },

這里主要看下第二步router的初始化:

    function init (app /* Vue component instance */) {
          //注意this是VueRouter實例,app是Vue實例
          var this$1 = this;
          //將當前Vue實例app存入VueRouter實例this.apps數組中,因為一
          //個應用可能不止一個Vue實例,故用數組保存。
          this.apps.push(app);
          // main app already initialized.
          if (this.app) {
            return
          }
          //將當前Vue實例app存在VueRouter實例this.app下
          this.app = app;
          var history = this.history;
          //當點擊一個路徑時,頁面會繪制該路徑對應的組件,history
          //.transitionTo方法就是干這個事的,后續再分析
          if (history instanceof HTML5History) {
            history.transitionTo(history.getCurrentLocation());
          } else if (history instanceof HashHistory) {
            var setupHashListener = function () {
              history.setupListeners();
            };
            history.transitionTo(
              history.getCurrentLocation(),
              setupHashListener,
              setupHashListener
            );
          }
          //監聽route,一旦route發生改變就賦值給app._route從而觸發頁面
          //更新,達到特定route繪制特定組件的目的
          history.listen(function (route) {
            this$1.apps.forEach(function (app) {
              app._route = route;
            });
          });
    };

beforeCreate函數執行完后,繼續Vue實例化的過程,這里就回到了Vue渲染頁面的過程,如下圖:

渲染過程.png

4、小結

以上分析可以看出引入vue-router時代碼的執行流程:

  1. 執行install方法。主要做了3件事:a、將$router和$route定義為Vue.prototype的存取器屬性;b、使用Vue.mixin方法創建了beforeCreate函數;c、擴充了Vue的默認組件,即增加了router-link和router-view兩個組件。
  2. 創建VueRouter實例。主要做了2件事:a、根據routes創建matcher;b、根據mode創建history。
  3. 創建Vue實例。主要做了1件事:調用beforeCreate函數,繼而執行router.init方法去完善router對象。
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,993評論 19 139
  • Vue 實例 屬性和方法 每個 Vue 實例都會代理其 data 對象里所有的屬性:var data = { a:...
    云之外閱讀 2,246評論 0 6
  • 三年只為一個人 為了你我丟了魂 我如何打開你心門 最后只剩這傷痕 一切要求我都做 而你劈腿再犯錯 想起曾經的承諾 ...
    殺了那只鬼閱讀 236評論 0 0