眾所周知,在
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) {
// 邏輯...
}
}
??????
?? 持續更文,關注我,你會發現一個踏實努力的寶藏前端??,讓我們一起學習,共同成長吧,
?? 喜歡的小伙伴記得點贊關注收藏喲,回看不迷路 ??
?? 歡迎大家評論交流, 蟹蟹??
本文來自博客園,作者:甜點cc,轉載請注明原文鏈接:https://www.cnblogs.com/all-smile/p/16597567.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/502187.html
標籤:其他
上一篇:什么是跨域?及7種跨域解決方法
