<template>
  <div>
    <button :disabled="countdown > 0" @click="sendVerificationCode">发送验证码</button>
    <span v-if="countdown > 0">{{ countdown }} 秒后重新发送</span>
  </div>
</template>
<script>
import { reactive, watchEffect } from 'vue'
export default {
  setup() {
    const state = reactive({
      countdown: 0,
      timer: null
    })
    const sendVerificationCode = () => {
      state.countdown = 60
      state.timer = setInterval(() => {
        if (state.countdown > 0) {
          state.countdown--
        } else {
          clearInterval(state.timer)
        }
      }, 1000)
    }
    watchEffect(() => {
      if (state.countdown === 0) {
        clearInterval(state.timer)
      }
    })
    return {
      state,
      sendVerificationCode
    }
  }
}
</script>
在 setup 函数中,我们创建了一个名为 state 的响应式对象,其中 countdown 属性表示还剩多少秒可以重新发送验证码。
sendVerificationCode 方法用于点击后发送验证码并开始倒计时。在 sendVerificationCode 方法中,我们将 countdown 设置为 60,并创建一个定时器,每隔一秒钟就将 countdown 减 1。当 countdown 为 0 时,我们清除定时器。
watchEffect 方法用于监听 countdown 的变化,当 countdown 变为 0 时,我们清除定时器。
在模板中,我们使用 disabled 属性禁用发送验证码按钮,直到倒计时结束。当 countdown 大于 0 时,我们显示剩余秒数。
        Made by 米云科技
        Code licensed under the
        Apache License v2.0.
        
        Based on
        Bootstrap.
        Icons from
        Font Awesome
        
                    豫ICP备18012765号-2
                        
            00001