How to limit the front end to make multiple requests

How to limit the front end to make multiple requests

Introduction to Lodash library:
https://blog.csdn.net/weixin_41957626/article/details/132640524

2. The method of restricting the front end to make multiple requests

2.1 Use the method of disabling the button

Disable Button: Before sending the request, disable the button and re-enable it until the request is complete. This prevents the user from clicking the button multiple times while the request is in progress.

When the OK button is clicked, the operation of restricting clicks is performed on the button.

<template>
  <div>
    <el-button :disabled="loading" @click="sendRequest">发送请求</el-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loading: false, // 控制按钮状态
    };
  },
  methods: {
    async sendRequest() {
      this.loading = true; // 禁用按钮
      try {
        // 发送请求
        await yourApiRequestFunction();
        // 请求成功后,启用按钮
      } catch (error) {
        // 处理错误情况
      } finally {
        this.loading = false; // 请求完成后,启用按钮
      }
    },
  },
};
</script>

2.2 Operation using anti-shake function

Pro test this is good

Using debounce or throttling: Debounce and throttling are techniques that control how often functions execute. You can use the debounce or throttle functions in the lodash library to ensure that the button click event only triggers a request within a certain time interval.

<template>
  <div>
    <el-button @click="debouncedSendRequest">发送请求</el-button>
  </div>
</template>

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

export default {
  methods: {
    debouncedSendRequest: debounce(async function() {
      try {
        // 发送请求
        await yourApiRequestFunction();
      } catch (error) {
        // 处理错误情况
      }
    }, 1000), // 1000 毫秒的防抖间隔
  },
};
</script>

Guess you like

Origin blog.csdn.net/weixin_41957626/article/details/132640556