main.js中
Vue.directive('throttle', {bind: (el, binding) => {let throttleTime = binding.value; // 防抖时间if (!throttleTime) { // 用户若不设置防抖时间,则默认2sthrottleTime = 2000;}let cbFun;el.addEventListener('click', event => {if (!cbFun) { // 第一次执行cbFun = setTimeout(() => {cbFun = null;}, throttleTime);} else {event && event.stopImmediatePropagation();}}, true);},
});
使用
<div @click="sayhello" v-throttle>提交</div>
实现效果,控制台2秒输出一次