官方文檔的解釋:vue
安裝 Vue.js 插件。若是插件是一個對象,必須提供 install 方法。若是插件是一個函數,它會被做爲 install 方法。install 方法調用時,會將 Vue 做爲參數傳入。
能夠在項目中使用vue.use()全局注入一個插件,從而不須要在每一個組件文件中import插件。例如:
不使用vue.use()注入插件:vue-router
const utils = require('./utils') // 或者 import utils from './utils'
使用vue.use()注入插件,最典型的案例:數組
import Vue from 'vue'; import Router from 'vue-router'; Vue.use(Router);
使用了vue.use()註冊插件以後就能夠在全部的vue文件中使用路由:this.$route
app
下面切入本文的主題。咱們知道了vue.use()怎麼用還不夠,還要知道它的內部是怎麼實現的。下面展現源碼:ide
import { toArray } from '../util/index' export function initUse (Vue: GlobalAPI) { 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 } }
vue.use()源碼中採用了flow的語法。flow語法,官方解釋是:函數
Flow is a static type checker for your JavaScript code. It does a lot of work to make you more productive. Making you code faster, smarter, more confidently, and to a bigger scale.
簡單的意思就是flow是JavaScript代碼的靜態類型檢查工具。官網連接
使用flow的好處就是:在編譯期對js代碼變量作類型檢查,縮短調試時間, 減小因類型錯誤引發的bug。咱們都知道js是解釋執行語言,運行的時候才檢查變量的類型,flow能夠在編譯階段就對js進行類型檢查。工具
下面將對vue.use()源碼進行解讀:ui
一、首先先判斷插件plugin是不是對象或者函數:Vue.use = function (plugin: Function | Object)
this
二、判斷vue是否已經註冊過這個插件installedPlugins.indexOf(plugin) > -1
若是已經註冊過,跳出方法插件
三、取vue.use參數。const args = toArray(arguments, 1)
四、toArray()取參數
代碼:
export function toArray (list: any, start?: number): Array<any> { start = start || 0 let i = list.length - start const ret: Array<any> = new Array(i) while (i--) { ret[i] = list[i + start] } return ret }
let i = list.length - start
意思是vue.use()方法傳入的參數,除第一個參數外(第一個參數是插件plugin),其餘參數都存儲到一個數組中,而且將vue對象插入到參數數組的第一位。最後參數數組就是[vue,arg1,arg2,...]
。
五、判斷插件是否有install方法,若是有就執行install()方法。沒有就直接把plugin當Install執行。
if (typeof plugin.install === 'function') { plugin.install.apply(plugin, args) } else if (typeof plugin === 'function') { plugin.apply(null, args) }
plugin.install.apply(plugin, args)
將install方法綁定在plugin
環境中執行,而且傳入args參數數組進install方法。此時install
方法內的this
指向plugin
對象。plugin.apply(null, args)
plugin內的this
指向null
.
最後告知vue該插件已經註冊過installedPlugins.push(plugin)
保證每一個插件只會註冊一次。
使用vue.use()
註冊插件,插件能夠是一個函數,能夠是一個帶有install
屬性的對象。無論是函數仍是install
方法,第一個參數老是vue
對象。
我的仍是喜歡使用將插件的功能方法寫在install
方法裏。由於install
內的this
指向的是plugin
對象自身,擴展性更好。