B站开了直播,工作日晚9点,大家都去投币。今天做了防抖函数,防止input控件的input事件短时间触发多次渲染延迟出现的问题,写在directives里,这里记录下源码
import Vue from "vue";
/**
* @description 防抖
* @param {function} fun 要延迟的方法
* @param {int} delay 要延迟时间
* @return {function} 延迟后函数
*/
const debounce = (fun = function() {}, delay = 800) => {
let timer = null; //缓存
return (...args) => {
//如果上一个还没执行 先清空
timer && clearTimeout(timer);
//执行当前的
timer = setTimeout(() => {
fun.apply(this, args);
timer = null;
}, parseInt(delay));
};
};
Vue.directive("debounce", {
inserted: function(el, binding, vnode) {
console.log(vnode);
// vnode.componentOptions.listeners.input;
// vnode.componentOptions.listeners.input.fns;
// function(){}.prototype.fns = [];
//如果是input
if (vnode.componentOptions && vnode.componentOptions.tag == "el-input") {
//得到原方法
let Fns = vnode.componentOptions.listeners.input;
//重写
let newfns = [];
Fns.fns.forEach((item, index) => {
//如果是第一 默认 不处理
if (index == 0) {
newfns.push(item);
}
//如果不是第一个防抖处理
else {
newfns.push(debounce(item));
}
});
//重新赋值
Fns.fns = newfns;
vnode.componentOptions.listeners.input = debounce(Fns);
}
}
});
//防抖
Vue.prototype.$_debounce = debounce;
用的时候在el-input标签 v-debounce 属性,能监听@input事件给自定义函数做防抖处理;