在 Vue.js 中实现防抖处理(Debounce)

1. 什么是防抖?

防抖是一种优化技术,指在连续触发某一操作时,只在最后一次触发后的一段时间内执行操作,避免频繁触发。对于登录按钮来说,防抖的作用是防止用户快速多次点击导致多次发送请求。


2. 实现步骤

(1)创建一个防抖函数

可以在组件中定义一个通用的防抖函数,或者使用第三方库(如 Lodash)提供的 debounce 函数。

(2)应用到 handleLogin 方法中

用防抖包装登录逻辑,确保快速连续点击只会触发一次登录请求。


3. 示例代码

完整实现:添加防抖逻辑
<script>
import axios from "axios";

// 防抖函数实现
function debounce(func, delay) {
  let timer;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}

export default {
  data() {
    return {
      username: "",
      password: "",
      error: "",
      isLoading: false, // 是否正在加载
    };
  },
  methods: {
    // 登录逻辑
    handleLogin() {
      if (!this.username || !this.password) {
        this.error = "用户名和密码不能为空";
        return;
      }

      this.isLoading = true;
      this.error = "";

      axios
        .post("http://localhost:3000/api/login", {
          username: this.username,
          password: this.password,
        })
        .then((response) => {
          if (response.data.success) {
            localStorage.setItem("token", response.data.token);
            localStorage.setItem("user", JSON.stringify(response.data.user));
            this.$emit("login-success", response.data.user);
            this.closeModal();
          } else {
            this.error = response.data.message || "用户名或密码错误";
          }
        })
        .catch((error) => {
          console.error("登录失败:", error);
          this.error = "登录失败,请稍后再试";
        })
        .finally(() => {
          this.isLoading = false;
        });
    },

    // 包装 handleLogin 方法,防止快速连续点击
    handleLoginDebounced: debounce(function () {
      this.handleLogin();
    }, 1000), // 防抖延迟 1 秒

    closeModal() {
      this.$emit("close");
    },
  },
};
</script>

4. 模板中使用防抖方法

修改登录按钮的点击事件,从直接调用 handleLogin 改为调用 handleLoginDebounced

<button type="submit" class="btn-primary" :disabled="isLoading" @click="handleLoginDebounced">
  <span v-if="isLoading">正在登录...</span>
  <span v-else>登录</span>
</button>

5. 使用 Lodash 实现防抖(可选)

如果你项目中已经安装了 Lodash,可以直接使用其 debounce 方法,代码更简洁。

安装 Lodash
npm install lodash
引入并使用防抖
import debounce from "lodash/debounce";

methods: {
  handleLogin() {
    // 登录逻辑...
  },

  handleLoginDebounced: debounce(function () {
    this.handleLogin();
  }, 1000), // 延迟 1 秒
},

6. 效果

  1. 快速点击按钮
    • 防抖会忽略重复的点击,只执行最后一次点击后的登录请求。
  2. 用户体验
    • 用户误操作时不会造成重复请求,避免对服务器造成压力。
  3. 代码清晰
    • 通过防抖封装,登录逻辑清晰可维护。

通过以上方式,防抖处理已经集成到登录按钮的逻辑中,让用户操作更加流畅,同时防止重复请求。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值