VueRouter源碼分析(2)--實(shí)例分析matcher和history

前言

本文是vue-router 2.x源碼分析的第二篇侨把,主要看matcher和history的處理過程鸿秆!

實(shí)例代碼

同上節(jié)

1铛漓、matcher

看下createMatcher函數(shù)

function createMatcher (routes,router) {
  var ref = createRouteMap(routes);
  var pathList = ref.pathList;
  var pathMap = ref.pathMap;
  var nameMap = ref.nameMap;

  function addRoutes (routes) {
    createRouteMap(routes, pathList, pathMap, nameMap);
  }
  function match (raw,currentRoute,redirectedFrom) {
    ...
  }
  function redirect (record,location) {
    ...
  }
  function alias (record,location,matchAs) {
    ...
  }
  function _createRoute (record,location,redirectedFrom) {
    ...
  }
  return {
    match: match,
    addRoutes: addRoutes
  }
}

該函數(shù)返回了一個(gè)包含match和addRoutes屬性的對(duì)象愕贡,這里主要看下createRouteMap函數(shù):

function createRouteMap (routes,oldPathList,oldPathMap,oldNameMap) {
  //pathList是用來控制path匹配優(yōu)先級(jí)的
  var pathList = oldPathList || [];
  var pathMap = oldPathMap || Object.create(null);
  var nameMap = oldNameMap || Object.create(null);
  //循環(huán)調(diào)用addRouteRecord函數(shù)完善pathList, pathMap, nameMap
  routes.forEach(function (route) {
    addRouteRecord(pathList, pathMap, nameMap, route);
  });
  // 確保通配符路徑總是在pathList數(shù)組末尾
  for (var i = 0, l = pathList.length; i < l; i++) {
    if (pathList[i] === '*') {
      pathList.push(pathList.splice(i, 1)[0]);
      l--;
      i--;
    }
  }
  return {
    pathList: pathList,
    pathMap: pathMap,
    nameMap: nameMap
  }
}

該函數(shù)將routes轉(zhuǎn)化成這樣的對(duì)象:

    ref:{
        nameMap:Object      //name路由
        pathList:Array(3)
        pathMap:Object      //path路由
        __proto__:Object
    }
    //本實(shí)例中是path路由潦嘶,生成的pathMap如下:
     pathMap:{
         "":Object
         /bar:Object
         /foo:Object
     }
     //其中第一個(gè)Object如下,該對(duì)象即是路由記錄record:
     {
        beforeEnter:undefined
        components:Object
        instances:Object
        matchAs:undefined
        meta:Object
        name:undefined
        parent:undefined
        path:""
        props:Object
        redirect:undefined
        regex:/^(?:\/(?=$))?$/i
        __proto__:Object
     }

可以看到createRouteMap主要調(diào)用了addRouteRecord函數(shù)伦忠,該函數(shù)如下:

function addRouteRecord (pathList,pathMap,nameMap,route,parent,matchAs) {
  var path = route.path;
  var name = route.name;
  //略過錯(cuò)誤處理部分
  ...
  //修正path
  var normalizedPath = normalizePath(path, parent);
  //根據(jù)傳入的route構(gòu)造路由記錄record
  var record = {
    path: normalizedPath,
    regex: compileRouteRegex(normalizedPath),
    components: route.components || { default: route.component },
    instances: {},
    name: name,
    parent: parent,
    matchAs: matchAs,
    redirect: route.redirect,
    beforeEnter: route.beforeEnter,
    meta: route.meta || {},
    props: route.props == null
      ? {}
      : route.components
        ? route.props
        : { default: route.props }
  };
  //處理嵌套路由
  if (route.children) {
    // Warn if route is named and has a default child route.
    // If users navigate to this route by name, the default child will
    // not be rendered (GH Issue #629)
    {
      if (route.name && route.children.some(function (child) { return /^\/?$/.test(child.path); })) {
        warn(
          false,
          "Named Route '" + (route.name) + "' has a default child route. " +
          "When navigating to this named route (:to=\"{name: '" + (route.name) + "'\"), " +
          "the default child route will not be rendered. Remove the name from " +
          "this route and use the name of the default child route for named " +
          "links instead."
        );
      }
    }
    route.children.forEach(function (child) {
      var childMatchAs = matchAs
        ? cleanPath((matchAs + "/" + (child.path)))
        : undefined;
      addRouteRecord(pathList, pathMap, nameMap, child, record, childMatchAs);
    });
  }
  //處理路由別名
  if (route.alias !== undefined) {
    //alias是數(shù)組
    if (Array.isArray(route.alias)) {
      route.alias.forEach(function (alias) {
        var aliasRoute = {
          path: alias,
          children: route.children
        };
        addRouteRecord(pathList, pathMap, nameMap, aliasRoute, parent, record.path);
      });
    //alias是字符串
    } else {
      var aliasRoute = {
        path: route.alias,
        children: route.children
      };
      addRouteRecord(pathList, pathMap, nameMap, aliasRoute, parent, record.path);
    }
  }
  //填充pathList,pathMap,nameMap
  if (!pathMap[record.path]) {
    pathList.push(record.path);
    pathMap[record.path] = record;
  }
  if (name) {
    if (!nameMap[name]) {
      nameMap[name] = record;
    } else if ("development" !== 'production' && !matchAs) {
      warn(
        false,
        "Duplicate named routes definition: " +
        "{ name: \"" + name + "\", path: \"" + (record.path) + "\" }"
      );
    }
  }
}

2省核、History

  • 先看HashHistory
  function HashHistory (router, base, fallback) {
    History.call(this, router, base);
    // check history fallback deeplinking
    if (fallback && checkFallback(this.base)) {
      return
    }
    ensureSlash();
  }

History長(zhǎng)這樣

  var History = function History (router, base) {
    this.router = router;
    //base最佳寫法:'/base',以斜杠開頭昆码,不以斜杠結(jié)尾
    this.base = normalizeBase(base);
    // start with a route object that stands for "nowhere"
    this.current = START;
    this.pending = null;
    this.ready = false;
    this.readyCbs = [];
    this.readyErrorCbs = [];
    this.errorCbs = [];
  };

History.prototype上有這些方法

History.prototype={
        listen:function(){...},
        onReady:function(){...},
        onError:function(){...},
        transitionTo:function(){...},
        confirmTransition:function(){...},
        updateRoute:function(){...}
}

//以下7.10新增
還記得上篇中router的初始化時(shí)關(guān)于history的處理嗎气忠,

 if (history instanceof HTML5History) {
        history.transitionTo(history.getCurrentLocation());
 } else if (history instanceof HashHistory) {
        var setupHashListener = function () {
              history.setupListeners();
         };
         history.transitionTo(
              history.getCurrentLocation(),
              setupHashListener,
              setupHashListener
          );
   }
  //監(jiān)聽route,一旦route發(fā)生改變就賦值給app._route從而觸發(fā)頁(yè)面
  //更新,達(dá)到特定route繪制特定組件的目的
  history.listen(function (route) {
        this$1.apps.forEach(function (app) {
              app._route = route;
        });
   });

我們以hash模式為主來分析赋咽,可以看到執(zhí)行了history.transitionTo方法旧噪,該方法接受了三個(gè)參數(shù)history.getCurrentLocation(),setupHashListener和setupHashListener。
先看getCurrentLocation方法脓匿,返回當(dāng)前hash值

  HashHistory.prototype.getCurrentLocation = function getCurrentLocation () {
       return getHash()
  };
//getHash函數(shù)如下:
function getHash () {
    // We can't use window.location.hash here because it's not
    // consistent across browsers - Firefox will pre-decode it!
    var href = window.location.href;
    var index = href.indexOf('#');
    return index === -1 ? '' : href.slice(index + 1)
}

再看transitionTo方法

History.prototype.transitionTo = function transitionTo (location, onComplete, onAbort) {
    var this$1 = this;
//調(diào)用match方法取得匹配到的route
    var route = this.router.match(location, this.current);
//調(diào)用confirmTransition方法    
this.confirmTransition(route, function () {
        this$1.updateRoute(route);
        onComplete && onComplete(route);
        this$1.ensureURL();

        // fire ready cbs once
        if (!this$1.ready) {
            this$1.ready = true;
            this$1.readyCbs.forEach(function (cb) { cb(route); });
        }
    }, function (err) {
        if (onAbort) {
            onAbort(err);
        }
        if (err && !this$1.ready) {
            this$1.ready = true;
            this$1.readyErrorCbs.forEach(function (cb) { cb(err); });
        }
    });
};

看看match方法

VueRouter.prototype.match = function match (raw,current,redirectedFrom) {
  return this.matcher.match(raw, current, redirectedFrom)
};
//this.matcher.match如下,該函數(shù)經(jīng)過層層調(diào)用最終返回了一個(gè)route對(duì)象淘钟,注意跟路由記錄record對(duì)象的區(qū)別
function match (raw, currentRoute,redirectedFrom) {
    var location = normalizeLocation(raw, currentRoute, false, router);
    var name = location.name;
    if (name) {
      var record = nameMap[name];
      {
        warn(record, ("Route with name '" + name + "' does not exist"));
      }
      var paramNames = record.regex.keys
        .filter(function (key) { return !key.optional; })
        .map(function (key) { return key.name; });

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

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

      if (record) {
        location.path = fillParams(record.path, location.params, ("named route \"" + name + "\""));
        return _createRoute(record, location, redirectedFrom)
      }
    } else if (location.path) {
      location.params = {};
      for (var i = 0; i < pathList.length; i++) {
        var path = pathList[i];
        var record$1 = pathMap[path];
        if (matchRoute(record$1.regex, location.path, location.params)) {
          return _createRoute(record$1, location, redirectedFrom)
        }
      }
    }
    // no match
    return _createRoute(null, location)
  }

未完待續(xù)。陪毡。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末日月,一起剝皮案震驚了整個(gè)濱河市袱瓮,隨后出現(xiàn)的幾起案子缤骨,更是在濱河造成了極大的恐慌爱咬,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,907評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件绊起,死亡現(xiàn)場(chǎng)離奇詭異精拟,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)虱歪,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,987評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門蜂绎,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人笋鄙,你說我怎么就攤上這事师枣。” “怎么了萧落?”我有些...
    開封第一講書人閱讀 164,298評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵践美,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我找岖,道長(zhǎng)陨倡,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,586評(píng)論 1 293
  • 正文 為了忘掉前任许布,我火速辦了婚禮兴革,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘蜜唾。我一直安慰自己杂曲,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,633評(píng)論 6 392
  • 文/花漫 我一把揭開白布袁余。 她就那樣靜靜地躺著擎勘,像睡著了一般。 火紅的嫁衣襯著肌膚如雪泌霍。 梳的紋絲不亂的頭發(fā)上货抄,一...
    開封第一講書人閱讀 51,488評(píng)論 1 302
  • 那天,我揣著相機(jī)與錄音朱转,去河邊找鬼蟹地。 笑死,一個(gè)胖子當(dāng)著我的面吹牛藤为,可吹牛的內(nèi)容都是我干的怪与。 我是一名探鬼主播,決...
    沈念sama閱讀 40,275評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼缅疟,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼分别!你這毒婦竟也來了遍愿?” 一聲冷哼從身側(cè)響起富玷,我...
    開封第一講書人閱讀 39,176評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤囚戚,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后澄阳,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體括授,經(jīng)...
    沈念sama閱讀 45,619評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡坞笙,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,819評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了荚虚。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片薛夜。...
    茶點(diǎn)故事閱讀 39,932評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖版述,靈堂內(nèi)的尸體忽然破棺而出梯澜,到底是詐尸還是另有隱情,我是刑警寧澤渴析,帶...
    沈念sama閱讀 35,655評(píng)論 5 346
  • 正文 年R本政府宣布晚伙,位于F島的核電站,受9級(jí)特大地震影響檬某,放射性物質(zhì)發(fā)生泄漏撬腾。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,265評(píng)論 3 329
  • 文/蒙蒙 一恢恼、第九天 我趴在偏房一處隱蔽的房頂上張望民傻。 院中可真熱鬧,春花似錦场斑、人聲如沸漓踢。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,871評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)喧半。三九已至,卻和暖如春青责,著一層夾襖步出監(jiān)牢的瞬間挺据,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,994評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工脖隶, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留扁耐,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,095評(píng)論 3 370
  • 正文 我出身青樓产阱,卻偏偏與公主長(zhǎng)得像婉称,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,884評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容