vue插件 学习记录

使用场景

插件通常用来为 Vue 添加全局功能。插件的功能范围没有严格的限制——一般有下面几种:
添加全局方法或者属性。如:vue-custom-element
添加全局资源:指令/过滤器/过渡等。如 vue-touch
通过全局混入来添加一些组件选项。如 vue-router
添加 Vue 实例方法,通过把它们添加到 Vue.prototype 上实现。
一个库,提供自己的 API,同时提供上面提到的一个或多个功能。如 vue-router


如何使用

通过全局方法 Vue.use() 使用插件。它需要在你调用 new Vue() 启动应用之前完成:

Vue.use(MyPlugin, { someOption: true })

开发插件

Vue.js 的插件应该暴露一个 install 方法。这个方法的第一个参数是 Vue 构造器,第二个参数是一个可选的选项对象:

MyPlugin.install = function (Vue, options...

更具体的:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值