背景
- 一个页面使用监听器,监听了页面的三个参数,页面初始化的时候,三个参数都发生了变化。发送了三次请求,页面却使用的是第二次请求的数据。
- 希望短时间内发生多次变化的时候,只发送一次请求
思路
这个需求可以通过使用防抖(debounce)函数来实现。防抖函数可以确保在一定时间内,无论函数被触发多少次,都只执行最后一次。
在Vue中,你可以使用lodash库的debounce
函数来实现这个功能。首先,你需要安装lodash库:
npm install lodash
然后在你的代码中引入lodash,并使用debounce
函数包装你的getList
方法:
import _ from 'lodash';
// ...
methods: {
// ...
getList: _.debounce(function() {
this.loading = true;
listFeeMonth(this.queryParams).then(response => {
this.feeMonthList = response.rows;
this.total = response.total;
this.loading = false;
});
}, 1000), // 1000毫秒内的多次调用,只会执行最后一次
// ...
}
这样,无论getList
方法在1秒内被调用多少次,都只会执行最后一次调用。