lodash防抖函数在v2和v3中的使用

206 阅读1分钟

用户短时间内连续快速点击按钮,导致同一个请求被发送多次,因此需要对按钮做防抖处理,使用lodash的防抖函数在v2和v3中的示例如下

安装lodash

npm install lodash

vue3

<template>
  <a-button type="primary" @click="handleClickDebounced">提交</a-button>
</template>

<script setup>
import { debounce } from 'lodash';
import { ref,onBeforeUnmount } from "vue";

// 原始函数,包含实际请求逻辑
const handleClick = () => {
  console.log('Button clicked! Sending request...');
  // 这里放置您的实际请求代码
};

// 使用Lodash的_.debounce创建防抖后的函数
const handleClickDebounced = debounce(handleClick, 1000); // 防抖延时为1000毫秒(1秒)

// 注意:在组件卸载时,应取消未执行的防抖任务以避免内存泄漏
onBeforeUnmount(() => {
  handleClickDebounced.cancel();
});
</script>

vue2

<template>
  <a-button type="primary" @click="handleClickDebounced">提交</a-button>
</template>

<script>
import { debounce } from 'lodash';

export default {
  data() {
    return {
      debouncedHandleClick: null,
    };
  },
  methods: {
    handleClick() {
      console.log('Button clicked! Sending request...');
      // 这里放置您的实际请求代码
    },
    initDebouncedHandleClick() {
      this.debouncedHandleClick = debounce(this.handleClick, 1000); // 防抖延时为1000毫秒(1秒)
    },
    handleClickDebounced() {
      this.debouncedHandleClick();
    },
  },
  created() {
    this.initDebouncedHandleClick();
  },
  beforeDestroy() {
    if (this.debouncedHandleClick) {
      this.debouncedHandleClick.cancel();
    }
  },
};
</script>