前言
本文是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時代碼的執行流程:
- 執行install方法。主要做了3件事:a、將$router和$route定義為Vue.prototype的存取器屬性;b、使用Vue.mixin方法創建了beforeCreate函數;c、擴充了Vue的默認組件,即增加了router-link和router-view兩個組件。
- 創建VueRouter實例。主要做了2件事:a、根據routes創建matcher;b、根據mode創建history。
- 創建Vue實例。主要做了1件事:調用beforeCreate函數,繼而執行router.init方法去完善router對象。