<template>
  <view class='container'>
    <button @click='sendRequest' :disabled='isRequesting'>{{ buttonText }}</button>
  </view>
</template>
<script>
export default {
  data() {
    return {
      isRequesting: false,
      buttonText: '发送请求'
    }
  },
  methods: {
    sendRequest() {
      if (this.isRequesting) {
        return;
      }

      this.isRequesting = true;
      this.buttonText = '请求中...';

      // 发送请求的代码,这里使用setTimeout模拟请求
      setTimeout(() => {
        // 请求完成后的逻辑
        this.isRequesting = false;
        this.buttonText = '发送请求';
      }, 2000);
    }
  }
}
</script>
<style>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

button {
  padding: 10px 20px;
  font-size: 16px;
}
</style>
<p>在上面的代码中,我们使用 <code>isRequesting</code> 来判断是否正在发送请求,初始值为 false 表示没有发送请求。点击按钮时,会触发 <code>sendRequest</code> 方法。在该方法中,首先检查 <code>isRequesting</code> 的值,如果为 true,则表示正在发送请求,直接返回。如果为 false,则设置 <code>isRequesting</code> 为 true,禁用按钮,并将按钮文字修改为'请求中...'。</p>
<p>接下来,我们使用 <code>setTimeout</code> 来模拟请求的延迟,2 秒后将 <code>isRequesting</code> 设置为 false,启用按钮,并将按钮文字修改为'发送请求'。</p>
<p>这样,当点击按钮发送请求时,如果正在发送请求,则不会触发第二次请求,直到请求完成后才能再次点击按钮发送请求。</p>

原文地址: https://www.cveoy.top/t/topic/p4Qy 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录