自定义防抖指令
一、用于查询、重置按钮实现防抖(v-debounce);
1.先创建一个js文件
- 创建一个debounce.js文件,放在scr/directives文件夹里面
export default (vue) => {
vue.directive('debounce', {
inserted: function(el, binding) {
let timer;
el.addEventListener("click", () => {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
binding.value();
}, 1000);
});
}
})
}
2.在main.js里面注册
import Debounce from './directives/debounce.js'
Debounce(Vue)
3.使用
v-debounce="serTableData"
二、用于实现元素(弹框)的拖拽;
1.创建dialogDrag.js文件
import Vue from 'vue';
Vue.directive('dialogDrag',{
bind(el, binding, vnode, oldVnode){
const dialogHeaderEl = el.querySelector('.el-dialog__header');
const dragDom = el.querySelector('.el-dialog');
dialogHeaderEl.style.cssText += ';cursor:move;';
dragDom.style.cssText += ';top:0px;';
const sty =(function(){
if(window.document.currentStyle){
return (dom, attr) => dom.currentStyle[attr];
}else{
return (dom, attr) => getComputedStyle(dom, false)[attr];
}
})()
dialogHeaderEl.onmousedown = (e){
const disX = e.clientX - dialogHeaderEl.offsetLeft;
const disY = e.clientY - dialogHeaderEl.offsetTop;
const screenWidth = document.body.clientWidth;
const screenHeight = document.documentElement.clientHeight;
const dragDomWidth = dragDom.offsetWidth;
const dragDomheight = dragDom.offsetHeight;
const minDragDomLeft = dragDom.offsetLeft;
const maxDragDomLeft = screenWidth - dragDom.offsetLeft - dragDomWidth;
const minDragDomTop = dragDom.offsetTop;
const maxDragDomTop = screenHeight - dragDom.offsetTop - dragDomheight;
let styL = sty(dragDom, 'left');
let styT = sty(dragDom, 'top');
if (styL.includes('%')) {
styL = +document.body.clientWidth * (+styL.replace(/\%/g, '') / 100);
styT = +document.body.clientHeight * (+styT.replace(/\%/g, '') / 100);
} else {
styL = +styL.replace(/\px/g, '');
styT = +styT.replace(/\px/g, '');
};
document.onmousemove = function(e){
let left = e.clientX - disX;
let top = e.clientY - disY;
if (-(left) > minDragDomLeft) {
left = -(minDragDomLeft);
} else if (left > maxDragDomLeft) {
left = maxDragDomLeft;
}
if(-(top)>minDragDomTop){
top=-(minDragDomTop);
}else if(top>maxDragDomTop){
top = maxDragDomTop;
}
dragDom.style.cssText += `;left:${left + styL}px;top:${top + styT}px;`;
}
document.onmouseup = function(e){
document.onmousemove = null;
document.onmouseup = null;
}
}
}
})
2.在mian.js中全局引入该文件
import './direstives/dialogDrag.js';
3.在需要拖拽的元素上写入v-dialogDrag即可实现;
<el-dialog v-dialogDrag :close-on-click-modal="false" title="弹框" :visible.sync="dialogVisible" width="630px" :before-close="close">
我是可以拖拽移动的弹框
</el-dialog>