在 Vue 開發中,實現一個功能有很多種方式可以選擇,這依賴於 Vue 強大的功能(指令、混合、過濾、插件等),本文介紹一下插件的開發使用。 ...
眾所周知,在
Vue
開發中,實現一個功能可以有很多種方式可以選擇,這依賴於Vue
強大的功能(指令、混合、過濾、插件等),本文介紹一下插件的開發使用。
Vue 插件
插件通常用來為 Vue 添加全局功能。插件的功能範圍沒有嚴格的限制——一般有下麵幾種:
-
添加全局方法或者 property。如:vue-custom-element
-
添加全局資源:指令/過濾器/過渡等。如 vue-touch
-
通過全局混入來添加一些組件選項。如 vue-router
-
添加 Vue 實例方法,通過把它們添加到 Vue.prototype 上實現。
-
一個庫,提供自己的 API,同時提供上面提到的一個或多個功能。如 vue-router
使用插件
vue引入的插件,如 element , 都需要提供 install 方法,因為 Vue.use() 方法會調用插件里的 install 方法
import Vue from 'vue'
import Element from 'element-ui'
Vue.use(Element)
全局組件
類似的
全局組件也是同樣的做法,在 install 方法裡面 進行 組件 註冊
import ColorIconComponents from './iconColor.vue'
const ColorIcon = {
install: function (Vue) {
Vue.component('ColorIcon', ColorIconComponents)
}
}
export default ColorIcon
綁定prototype
數組對象等綁定自定義方法
// path: src/utils/customFn.js
export default {
install(Vue) {
// 數組對象排序 asc-升序 des-降序
Array.prototype.sortListObjByKey = function (key, order = 'asc') {
const that = this
const comparefn = (obj1, obj2) => {
if (order === 'asc') {
return obj1[key] - obj2[key]
} else {
return obj2[key] - obj1[key]
}
}
return that.sort(comparefn)
}
}
}
使用
// path: src/main.js
import customFn from "./libs/customFn";
Vue.use(customFn)
開發插件範式
Vue.js 的插件應該暴露一個 install 方法。這個方法的第一個參數是 Vue 構造器,第二個參數是一個可選的選項對象:
MyPlugin.install = function (Vue, options) {
// 1. 添加全局方法或 property
Vue.myGlobalMethod = function () {
// 邏輯...
}
// 2. 添加全局資源
Vue.directive('my-directive', {
bind (el, binding, vnode, oldVnode) {
// 邏輯...
}
...
})
// 3. 註入組件選項
Vue.mixin({
created: function () {
// 邏輯...
}
...
})
// 4. 添加實例方法
Vue.prototype.$myMethod = function (methodOptions) {
// 邏輯...
}
}