使用場景
插件通常用來為 Vue 添加全局功能。插件的功能範圍沒有嚴格的限制——一般有下面幾種:
添加全局方法或者屬性。如:vue-custom-element
添加全局資源:指令/過濾器/過渡等。如 vue-touch
通過全局混入來添加一些元件選項。如 vue-router
添加 Vue 執行個體方法,通過把它們添加到 Vue.prototype 上實作。
一個庫,提供自己的 API,同時提供上面提到的一個或多個功能。如 vue-router
如何使用
通過全局方法 Vue.use() 使用插件。它需要在你調用 new Vue() 啟動應用之前完成:
開發插件
Vue.js 的插件應該暴露一個 install 方法。這個方法的第一個參數是 Vue 構造器,第二個參數是一個可選的選項對象:
更具體的:
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) {
// 邏輯...
}
}
執行個體
// src/utils/js/MyDirectPlugin
MyDirectPlugin.install = function (Vue, options) {
Vue.directive('dialogDrag', {
bind(el, binding, vNode, oldNode) {
// 目前寬高
let nowWidth = 0;
let nowHeight = 0;
// 目前頂部高度
let nowMarginTop = 0;
// 擷取彈框頭部
const dialogHeaderEl = el.querySelector('.el-dialog__header');
// 彈窗
const dragDom = el.querySelector('.el-dialog');
//清除選擇頭部文字效果
//dialogHeaderEl.onselectstart = new Function("return false");
dialogHeaderEl.style.cursor = 'move';
擷取原有屬性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null);
const sty = dragDom.currentStyle || window.getComputedStyle(dragDom, null);
let moveDown = (e) => {
// 滑鼠按下, 計算目前元素距離可視區的距離
const distX = e.clientX;
const distY = e.clientY;
// 擷取 到的值px
let styL, styT;
styL = +sty.left.replace(/\px/g, '');
styT = +sty.top.replace(/\px/g, '');
document.onmousemove = function(mouse) {
const l = mouse.clientX - distX;
const t = mouse.clientY - distY;
dragDom.style.left = `${(l + styL)}px`;
dragDom.style.top = `${(t + styT)}px`;
}
document.onmouseup = function (e) {
document.onmousemove = null;
document.onmouseup = null;
}
} // end moveDown
dialogHeaderEl.onmousedown = moveDown;
}
})
}
export default MyDirectPlugin
// main.js
import MyDirectPlugin from '@/utils/js/MyDirectPlugin'
Vue.use(myDirect)
其他執行個體
這裡有個很好的插件示例,還有上傳到npm的流程介紹
轉載:
作者:LWH🖥
來源; https://juejin.im/post/5e8ff823f265da47d96213b1
寫個檢視原圖元件并上傳到NPM