1、手动实现防抖函数
<template>
<div>
<button @click="handleClick()">点击</button>
</div>
</template>
<script>
export default {
data() {
return {
clickTimer: null
}
},
methods: {
handleClick() {
if (this.clickTimer) {
clearTimeout(this.clickTimer)
}
this.clickTimer = setTimeout(() => {
console.log('handleClick')
}, 500)
},
}
}
</script>
2、手动实现防抖函数2
<template>
<div>
<button @click="handleClick()">点击</button>
</div>
</template>
<script>
export default {
data() {
return {
debouncedClick: null
}
},
created() {
this.debouncedClick = this.debounce(this.doSomething, 500);
},
methods: {
doSomething() {
console.log('doSomething');
},
handleClick() {
this.debouncedClick();
},
debounce(func, wait) {
let timeout;
return function() {
const context = this
const args = arguments
if (timeout) {
clearTimeout(timeout)
}
timeout = setTimeout(() => {
func.apply(context, args)
}, wait)
}
}
}
}
</script>
3、使用Lodash的debounce函数
<template>
<div>
<button @click="handleClick()">点击</button>
</div>
</template>
<script>
import _ from 'lodash';
export default {
data() {
return {
clickTimer: null,
debouncedClick: _.debounce(this.doSomething, 500)
}
},
methods: {
doSomething() {
console.log('doSomething');
},
handleClick() {
this.debouncedClick();
},
}
}
</script>