vue 优雅的实现防抖和节流
防抖(debounce): n 秒后执行该事件,若在n秒后被重复触发,则重新计时
节流(throttle): n 秒内只运行一次,若在n秒内重复触发,只有一次生效
安装 lodash
yarn add lodash
npm i lodash -s | npm install --save
导入lodash
import _ form "lodash"
_: 根据需求进行自定义
案例:
<template>
<button @click="btn1"></button>
</template>
<script>
methods: {
btn1 () {
this.btn2();
this.btn3();
},
btn2:_.debounce(function(){
console.log('防抖')
},1000),
btn2:_.throttle(function(){
console.log('节流')
},1000)
}
</script>
vue3 中优雅的使用防抖和节流
<template>
<button @click="btn1"></button>
<button @click="btn2"></button>
</template>
<script>
setup() {
//防抖
const btn1 = _.debounce(function() {
console.log('防抖');
}, 2000);
//节流
const btn2 = _.throttle(function() {
console.log('节流');
}, 2000);
return {
btn1,
btn2,
};
</script>