防抖的作用 防止按钮在短时间内被多次点击,使用防抖函数限制规定时间内只能点击一次。
思路:
- 定义一个延迟执行的方法,如果在延迟时间内再调用该方法,则重新计算执行时间。
- 将时间绑定在 click 方法上。
全局定义自定义指令(防抖)
main.js
Vue.directive(
'shake', {
inserted: function (el, binding) {
let timer;
el.addEventListener("click", () => {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
binding.value();
}, 1000);
});
},
}
)
使用页面:
<template>
<div style="width: 100%; overflow: hidden">
<div class="info">
<!-- <h4>基本信息</h4> -->
<button v-shake='shake'>22222</button>
</div>
</div>
</template>
<script>
export default {
methods:{
shake(){
console.log('按钮被点击');
}
}
};
</script>