前言
本文是vue-router 2.x源碼分析的第一篇喷屋,主要看vue-router的整體結(jié)構(gòu)元践!
實例代碼
<!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>' }
//創(chuàng)建router實例
const router = new VueRouter({
routes: [
{ path: '/', component: Home },
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
]
})
//創(chuàng)建vue實例
new Vue({
router
}).$mount('#app')
</script>
</body>
</html>
1腺律、執(zhí)行Vue.use(VueRouter)
VueRouter是作為Vue的插件存在的漏健,使用Vue.use(VueRouter)的方式侵入Vue非凌,這個操作在引入vue-router.js時就執(zhí)行了,Vue.use方法會執(zhí)行VueRouter的install方法涤垫,看下該方法:
function install (Vue) {
if (install.installed) { return }
install.installed = true;
_Vue = Vue;
//1姑尺、將$router和$route定義為Vue.prototype的存取器屬性竟终,以便所有組
//件都可以訪問到蝠猬,注意這個get函數(shù),是返回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構(gòu)造了一個beforeCreate函數(shù)榆芦,該函數(shù)會在vue實例創(chuàng)建的
// 時候被調(diào)用
Vue.mixin({
beforeCreate: function beforeCreate () {
if (isDef(this.$options.router)) {
this._router = this.$options.router;
//執(zhí)行router的初始化
this._router.init(this);
//route定義為響應式以便能在其改變時觸發(fā)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;
}
以上三件事執(zhí)行完,就開始new VueRouter了
2匆绣、創(chuàng)建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驻右、根據(jù)傳入的options.routes創(chuàng)建matcher對象
this.matcher = createMatcher(options.routes || [], this);
//2、根據(jù)傳入的options.mode創(chuàng)建不同的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創(chuàng)建matcher
//routes長這樣:
routes: [
{ path: '/', component: Home },
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
]
//經(jīng)過createMatcher處理的matcher長這樣:
matcher:{
addRoutes:function addRoutes(routes)
match:function match( raw, currentRoute, redirectedFrom )
__proto__:Object
}
- 再看第二件事堪夭,由mode創(chuàng)建history
//mode默認值為'hash',故會創(chuàng)建HashHistory實例
history:{
base:""
current:Object
errorCbs:Array(0)
pending:null
ready:false
readyCbs:Array(0)
readyErrorCbs:Array(0)
router:VueRouter
__proto__:History
}
最后創(chuàng)建的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
}
創(chuàng)建的具體細節(jié)以后會分析。這兩件事情做完就開始new Vue(options)了拣凹。
3森爽、創(chuàng)建Vue實例(new Vue(options))
創(chuàng)建Vue實例的過程中會調(diào)用beforeCreate函數(shù),故在第一節(jié)中定義的beforeCreate會得到執(zhí)行:
function beforeCreate () {
if (isDef(this.$options.router)) {
//1嚣镜、正式將第二節(jié)創(chuàng)建的router實例掛在this._router上爬迟,這個this
//是根實例,相當于子組件中的this.$root菊匿,因此在子組件中能通過t
//his.$router訪問到
this._router = this.$options.router;
//2付呕、執(zhí)行router的初始化
this._router.init(this);
//3、將_route定義為響應式以便能在其改變時觸發(fā)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數(shù)組中,因為一
//個應用可能不止一個Vue實例佩厚,故用數(shù)組保存活箕。
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方法就是干這個事的育韩,后續(xù)再分析
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ā)頁面
//更新,達到特定route繪制特定組件的目的
history.listen(function (route) {
this$1.apps.forEach(function (app) {
app._route = route;
});
});
};
beforeCreate函數(shù)執(zhí)行完后闺鲸,繼續(xù)Vue實例化的過程筋讨,這里就回到了Vue渲染頁面的過程,如下圖:
4摸恍、小結(jié)
以上分析可以看出引入vue-router時代碼的執(zhí)行流程:
- 執(zhí)行install方法悉罕。主要做了3件事:a、將$router和$route定義為Vue.prototype的存取器屬性立镶;b壁袄、使用Vue.mixin方法創(chuàng)建了beforeCreate函數(shù);c媚媒、擴充了Vue的默認組件嗜逻,即增加了router-link和router-view兩個組件。
- 創(chuàng)建VueRouter實例缭召。主要做了2件事:a栈顷、根據(jù)routes創(chuàng)建matcher逆日;b、根據(jù)mode創(chuàng)建history萄凤。
- 創(chuàng)建Vue實例室抽。主要做了1件事:調(diào)用beforeCreate函數(shù),繼而執(zhí)行router.init方法去完善router對象靡努。