前言
主要记录一下,lodash中的防抖如何取消,也会写一点防抖跟节流的具体运用。
一、在vue中如何用lodash防抖与取消?
//注意:我这个需求是自动保存数据的,一个是手动保存跟自动保存,因为有可能手动会与自动
//两个保存起冲突,所以当手动保存时,就把自动的清了
//引入
import _ from "lodash";
watch: {
Data: {
handler(newV, oldV) {
this.debounceTraverse(newV);
},
deep: true,
},
},
created() {
// 防抖
this.debounceTraverse = _.debounce(function (obj) {
this.traverseObject(obj);//这个就是处理数据的
}, 10000);//一旦数据变动,就10秒一保存
},
//保存
onSubmit() {
//cancel这个函数就是取消的
this.debounceTraverse.cancel();
},
注意:只有在防抖函数没有执行之前才能成功取消防抖操作,一但防抖函数已经执行,就无法取消操作
二、在js中使用lodash中的debounce函数,与取消
import {debounce} from 'lodash'
//创建一个延迟执行的函数数
const delayedFunction = debounce (()=>{
console.log('执行延迟函数');
},1000);
//调用该函数,但是在500毫秒内取消执行
delayedFunction();
setTimeout(() => {
delayedFunction.cancel()
},500):
三,几个比较常见的需求
假设,我们有一个搜索框,用户在输入时会触发搜索函数,我们希望在用户停止输入一段时间后才执行搜索函数,以避免频繁的搜索请求:
<template>
<div>
<input type="text" v-model="query" @input="search">
</div>
</template>
<script>
import { debounce } from 'lodash';
export default {
data() {
return {
query: '',
};
},
methods: {
search: debounce(function() {
// 执行搜索操作
}, 500), // 等待500毫秒后执行搜索函数
},
};
</script>
解释:我们使用了debounce函数来创建了一个新的函数,该函数将在用户输入时被多次调用,但只有在用户停止输入500毫秒后,才会执行实际的搜索函数。这样可以有效地减少搜索请求的数量,并提高搜索的性能。
假设,我们有一个滚动列表,用户滚动时会触发scroll事件,我们希望在用户滚动时只执行一次实际的处理函数,以避免过多的处理操作:
<template>
<div ref="container" @scroll="handleScroll"></div>
</template>
<script>
import { throttle } from 'lodash';
export default {
mounted() {
// 监听滚动事件
const container = this.$refs.container;
container.addEventListener('scroll', this.handleScrollThrottled);
},
beforeDestroy() {
// 移除滚动事件监听
const container = this.$refs.container;
container.removeEventListener('scroll', this.handleScrollThrottled);
},
methods: {
handleScroll: function() {
// 执行滚动处理操作
},
handleScrollThrottled: throttle(function() {
this.handleScroll();
}, 500), // 每500毫秒执行一次滚动处理操作
},
};
</script>
解释:我们使用了throttle函数来创建了一个新的函数,该函数将在用户滚动时被多次调用,但只有每500毫秒才会执行实际的处理函数。这样可以有效地减少处理操作的数量,并提高滚动的性能。同时,我们还在组件的mounted和beforeDestroy生命周期钩子中添加了对滚动事件的监听和移除操作,以避免出现内存泄漏问题。