### 插件
插件通常用來爲 Vue 添加全局功能。插件的功能範圍沒有嚴格的限制——一般有下面幾種:
1. 添加全局方法或者屬性。如: vue-custom-element
2. 添加全局資源:指令/過濾器/過渡等。如 vue-touch
3. 通過全局混入來添加一些組件選項。如 vue-router
4. 添加 Vue 實例方法,通過把它們添加到 Vue.prototype 上實現。
5. 一個庫,提供自己的 API,同時提供上面提到的一個或多個功能。如 vue-router
### 使用插件
```javascript
import {MyPlugin} from "MyPlugin"
Vue.use(MyPlugin, { someOption: true })
```
Vue.use 會自動阻止多次註冊相同插件,屆時即使多次調用也只會註冊一次該插件。
### 開發插件
Vue.js 的插件應該暴露一個 install 方法。這個方法的第一個參數是 Vue 構造器,第二個參數是一個可選的選項對象:
```javascript
MyPlugin.install = function (Vue, options) {
// 1. 添加全局方法或屬性
Vue.myGlobalMethod = function () {
// 邏輯...
}
// 2. 添加全局資源
Vue.directive('my-directive', {
bind (el, binding, vnode, oldVnode) {
// 邏輯...
}
...
})
// 3. 注入組件選項
Vue.mixin({
created: function () {
// 邏輯...
}
...
})
// 4. 添加實例方法
Vue.prototype.$myMethod = function (methodOptions) {
// 邏輯...
}
}
```
或者插件直接暴露一個函數方法
```javascript
export default function (Vue, options) {
//...
}
```
### 源碼分析
path: vue-dev/src/core/global-api/use.js
```javascript
/* @flow */
import { toArray } from '../util/index'
// 初始化 Vue.use 方法
export function initUse (Vue: GlobalAPI) {
// 綁定全局Vue.use方法,(plugin: Function | Object)通過flow做類型檢查,參數類型爲Function | Object
Vue.use = function (plugin: Function | Object) {
// Vue._installedPlugins綁定數組,存儲已經執行的插件,保證插件只install一次,防止插件被多次use
const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
// 如果插件被多次use,則return this
if (installedPlugins.indexOf(plugin) > -1) {
return this
}
/**
* toArray處理arguments
* 如 Vue.use(Plugin, {params: true})
* args = [Vue, {params: true}]
*/
const args = toArray(arguments, 1) // [{params: true}]
args.unshift(this) // [Vue, {params: true}]
//如果Plugin.install存在即執行,否則如果Plugin是一個函數,則執行。並且傳入args參數
if (typeof plugin.install === 'function') {
plugin.install.apply(plugin, args)
} else if (typeof plugin === 'function') {
plugin.apply(null, args)
}
// installedPlugins 把use完成的插件放入插件池
installedPlugins.push(plugin)
return this
}
}
```
path: vue-dev/src/shared/util.js
```javascript
// toArray
// 返回一個新數組並刪除原數組前start個元素
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
}
```