詳解vue-router 初始化時做了什么
最近因為業(yè)務(wù)需要,實現(xiàn)了一個簡單的前端 router,正好也來看一下 vue router 是怎么實現(xiàn)的。這次先來一起看看 vue-router 初始化時做了什么。
vue router 的初始化使用步驟
我們首先來看 vue-router 的使用步驟,然后再分別去看各個步驟都發(fā)生了什么。
使用 vue-router 需要經(jīng)過一下幾個步驟:
引入 vue-router:
import VueRouter from 'vue-router';
利用 vue 的插件機制,加載 vue-router:
Vue.use(VueRouter);
實例化 VueRouter:
const router = new VueRouter({
routes
})
實例化 Vue:
const app = new Vue({
router
}).$mount('#app');
Vue 的插件機制
vue 提供了一個 use 方法,來加載插件:
Vue.use = function (plugin: Function | Object) {
const installedPlugins = (this._installedPlugins || (this._installedPlugins = []));
if (installedPlugins.indexOf(plugin) > -1) {
return this;
}
// additional parameters
const args = toArray(arguments, 1);
args.unshift(this);
if (typeof plugin.install === 'function') {
plugin.install.apply(plugin, args);
} else if (typeof plugin === 'function') {
plugin.apply(null, args);
}
installedPlugins.push(plugin);
return this;
}
該方法首先檢查插件是否已經(jīng)加載,如果已經(jīng)加載,直接返回 this。
如果沒有加載過,會取所有的參數(shù),并將 this 放在第一個。優(yōu)先執(zhí)行 plugin.install 方法,若不能執(zhí)行,則直接執(zhí)行 plugin 自身。
最后將 plugin push 到插件列表中。
那么我們就需要看 VueRouter 的 install 方法做了什么,VueRouter 類定義在 src/index.js 文件中。
利用 vue 的插件機制,加載 vue-router
入口文件 index.js 對外 export 了一個 VueRouter 類。VueRouter 類包含了 router 的各種方法,我們直接先來看一下 install 方法。
install 方法在 index.js 中綁定在 VueRouter 類上:
import { install } from './install'
VueRouter.install = install
它的實際實現(xiàn)是在 ./install.js 中,install 方法主要做了以下幾個事情:
1、設(shè)置了兩個 mixin:beforeCreate 和 destroyed。
Vue.mixin({
beforeCreate () {
if (isDef(this.$options.router)) {
this._routerRoot = this
this._router = this.$options.router
this._router.init(this)
Vue.util.defineReactive(this, '_route', this._router.history.current)
} else {
this._routerRoot = (this.$parent && this.$parent._routerRoot) || this
}
registerInstance(this, this)
},
destroyed () {
registerInstance(this)
}
})
2、在 Vue 上綁定 $route 和 $router。
Object.defineProperty(Vue.prototype, '$router', {
get () { return this._routerRoot._router }
})
Object.defineProperty(Vue.prototype, '$route', {
get () { return this._routerRoot._route }
})
3、注冊兩個組件,View 和 Link。
Vue.component('RouterView', View)
Vue.component('RouterLink', Link)
4、設(shè)置 beforeRouteEnter、beforeRouteLeave 和 beforeRouteUpdate 的 merge 策略。merge 策略的介紹可以見 這里 ,簡單來說就是有重復(fù)的值時如何合并。
const strats = Vue.config.optionMergeStrategies // use the same hook merging strategy for route hooks strats.beforeRouteEnter = strats.beforeRouteLeave = strats.beforeRouteUpdate = strats.created
實例化 VueRouter
我們來看一下 VueRouter 的構(gòu)造函數(shù)。首先,constructor 會初始化一些屬性:
this.app = null this.apps = [] this.options = options this.beforeHooks = [] this.resolveHooks = [] this.afterHooks = [] this.matcher = createMatcher(options.routes || [], this)
其中 matcher 比較重要,后面會詳細(xì)說。
之后會決定使用哪種模式:
let mode = options.mode || 'hash'
this.fallback = mode === 'history' && !supportsPushState && options.fallback !== false
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:
if (process.env.NODE_ENV !== 'production') {
assert(false, `invalid mode: ${mode}`)
}
}
由于 history 模式中的pushstate方法還有一些瀏覽器沒有支持。history 模式在瀏覽器不支持時會回退到hash模式。
之后根據(jù)不同模式選擇實例化不同模式的history類,可以看到 hash 模式和 history 模式分別對應(yīng)了 HashHistory 和 HTML5History 兩個類。
此外,如果是服務(wù)器端渲染,需要進行 router 匹配來獲取要渲染的頁面。此時服務(wù)器環(huán)境中沒有history api,因此要自行抽象實現(xiàn)一個,就是 AbstractHistory。
實例化 Vue
實例化為Vue 類時,會將 VueRouter 的實例傳入,這個變量放在 this.$options.router 中。由于 vue router 時以插件形式引入的,因此 這個 this.$options.router 還是給 vue router 自身來用的。
vue router 初始化所做的事情就是這些,下篇博客我們來一起看一下 vue router 實際運行時發(fā)生了什么。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
vue如何使用html2canvas和JsPDF導(dǎo)出pdf組件
這篇文章主要介紹了vue如何使用html2canvas和JsPDF導(dǎo)出pdf組件問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-09-09
vue 使用鼠標(biāo)滾動加載數(shù)據(jù)的例子
今天小編就為大家分享一篇vue 使用鼠標(biāo)滾動加載數(shù)據(jù)的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-10-10
ElementUI實現(xiàn)在下拉列表里面進行搜索功能詳解
有時候需要用到下拉列表全選和搜索,下面這篇文章主要給大家介紹了關(guān)于ElementUI實現(xiàn)在下拉列表里面進行搜索功能的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-04-04

