最近因?yàn)闃I(yè)務(wù)需要,實(shí)現(xiàn)了一個簡單的前端 router,正好也來看一下 vue router 是怎么實(shí)現(xiàn)的。這次先來一起看看 vue-router 初始化時做了什么。
vue router 的初始化使用步驟
我們首先來看 vue-router 的使用步驟,然后再分別去看各個步驟都發(fā)生了什么。
使用 vue-router 需要經(jīng)過一下幾個步驟:
引入 vue-router:
import VueRouter from 'vue-router';
利用 vue 的插件機(jī)制,加載 vue-router:
Vue.use(VueRouter);
實(shí)例化 VueRouter:
const router = new VueRouter({routes})實(shí)例化 Vue:
const app = new Vue({router}).$mount('#app');Vue 的插件機(jī)制
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 的插件機(jī)制,加載 vue-router
入口文件 index.js 對外 export 了一個 VueRouter 類。VueRouter 類包含了 router 的各種方法,我們直接先來看一下 install 方法。
install 方法在 index.js 中綁定在 VueRouter 類上:
import { install } from './install'VueRouter.install = install它的實(shí)際實(shí)現(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 }})
新聞熱點(diǎn)
疑難解答
圖片精選