1、先建一个js文件
建一个debounce.js文件,放在src/directives文件夹里面
export default (vue) => {
/**
* 绑定方法
* @param {Object} el - The element the directive is bound to.
* @param {Object} binding - An vue directive object
*/
vue.directive('debounce', { //防抖函数指令
inserted: function(el, binding) {
let timer;
el.addEventListener("click", () => {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
//关键点:vue 的自定义指令传递的参数binding 如果是一个函数,则通过 binding.value()来执行,通过上述示例,还可以传递比如事件, 绑定对象之类的
binding.value();
}, 1000);
});
}
})
}
2、在mian.js里面注册
import Debounce from './directives/debounce.js' //防抖自定义指令
Debounce(Vue)
3、使用
在组件中button按钮添加该指令即可实现防抖
v-debounce="getTableData"