import Vue from 'vue' /** * 按钮防抖,300毫秒内只触发一次请求 * 区分了一下传参和不传参的情况 */ // 不传参数,用法:v-debounce="test_debounce" Vue.directive('debounce', { inserted: function(el, binding) { let timer el.addEventListener('click', () => { if (timer) { clearTimeout(timer) } console.log(binding.value) timer = setTimeout(() => { binding.value() }, 300) }) }, }) // 传入参数,用法:v-debounce="{ handler: test_debounce, params: '传入的参数' }" Vue.directive('params-debounce', { inserted: function(el, binding) { let timer el.addEventListener('click', () => { if (timer) { clearTimeout(timer) } timer = setTimeout(() => { binding.value.handler(binding.value.params) }, 300) }) }, })
ps:记得在main.js中引入
标签:el,防抖,vue,自定义,debounce,binding,timer,value From: https://www.cnblogs.com/lyt520/p/17620714.html