How does element-ui send a verification code on the input and implement a 60-second countdown?

To send a verification code and implement a 60-second countdown on Element UI's `<el-input>`, you can combine Vue.js data binding and timers. The following is a simple Vue single-file component sample code:

<template>
  <div>
    <el-input v-model="phone" placeholder="请输入手机号码"></el-input>
    <el-button @click="sendCode" :disabled="isSending || countdown > 0">
      {
   
   { isSending ? '发送中...' : countdown > 0 ? `${countdown}秒后重试` : '发送验证码' }}
    </el-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      phone: '',
      isSending: false,
      countdown: 0,
    };
  },
  methods: {
    sendCode() {
      if (this.countdown > 0 || this.isSending) {
        return; // 防止重复点击发送
      }

      // 假设在这个方法中实现发送验证码的逻辑
      // 可以调用sendVerificationCode()方法发送验证码
      // 这里只是简单模拟发送过程
      this.isSending = true;
      this.startCountdown();

      setTimeout(() => {
        // 假设发送成功后将isSending重置为false
        this.isSending = false;
      }, 2000); // 这里使用2秒的延迟来模拟发送过程,你需要替换为实际的发送逻辑
    },
    startCountdown() {
      this.countdown = 60;
      const timer = setInterval(() => {
        this.countdown--;
        if (this.countdown <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    },
  },
};
</script>

In the above example, we use `isSending` to control whether the button is disabled and display text. When the user clicks the send button, the `sendCode` method will first check whether `countdown` is greater than 0, and whether `isSending` is true. If `countdown` is greater than 0 or `isSending` is true, the logic of sending the verification code will not be executed to prevent the user from clicking send repeatedly. Then, start sending the verification code and start the countdown.

The `startCountdown` method is used to start a 60-second countdown. It uses `setInterval` to update the value of `countdown` every 1 second, and clears the timer after the countdown ends.

In this way, when the user clicks the send button, the button will display "Sending...", and after the sending is successful, the button will display a countdown within 60 seconds. After the countdown ends, the button will return to "Sending Verification Code", and the user can Click Send again. Please note that the verification code sending and countdown in the above example are only simulations, you need to adjust the code according to the actual verification code sending logic and timer requirements.

Guess you like

Origin blog.csdn.net/qq_58647634/article/details/131868333