在Vue中使用防抖和节流优化
1. utils.js
/* 防抖 */
function debounce(func, delay) {
let timer = null;
return function () {
if (timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(() => {
func(...arguments);
}, delay);
};
}
/* 节流 */
function throttle(func, delay) {
let time = null;
return function () {
let args = Array.from(arguments);
if (time === null) {
time = setTimeout(() => {
func(...args);
clearTimeout(time);
time = null;
}, delay);
}
};
}
2. demo.vue内引用
<template>
<div>
<div class="container" @scroll="onScroll">
</div>
</div>
</template>
<script>
import { debounce,throttle } from '../../utils';
export default {
name: '',
data() {
return {
}
},
created() {
// 防抖
this.onScroll = debounce(this.funScroll,1000);
// 节流
this.onScroll = throttle(this.funScroll,1000);
},
methods: {
funScroll(){
console.log('滚动事件')
}
}
</script>
<style lang = "less" scoped>
</style>