自定义指令方式封装防抖节流函数
新建directives.js文件
import Vue from 'vue'
Vue.directive('debounce', {
inserted: function (el, binding) {
let timer = null;
el.addEventListener('click', () => {
if(timer) clearTimeout(timer);
timer = setTimeout(()=>{
binding.value();
},1000)
})
}
})
Vue.directive('throttle',{
inserted: function(el, binding){
el.addEventListener('click', () => {
if (!el.disabled) {
el.disabled = true;
setTimeout(() => {
binding.value();
el.disabled = false;
}, 1000)
}
})
}
})
main.js 引入
import directive from './directives.js'
Vue.use(directive)
页面使用方法
<div v-debounce="submit">提交</div>