发送验证码setInterval和setTimeout

在这里插入图片描述

    <div class="text-align-center" style='padding:20px;height:80px;position:relative;background:#fff;'>
      <v-text-field
        label="验证码"
        style='width:60%;'
      ></v-text-field>
      <v-btn @click="send()" :disabled = 'disabled' rounded depressed style='position:absolute;top:32px;right:20px;width:30%;'>{{text}}</v-btn>
    </div>
data中定义:
  text: '发送验证码',
   timer: '',
   time: 0,
   disabled: false
    send () {
      this.time = 60
      this.disabled = true
      // setInterval
      this.timer = setInterval(this.getTimer, 1000)
      // this.timer = setInterval(() => {
      //   this.time--
      //   this.text = this.time + 's'
      //   if (this.time < 1) {
      //     this.disabled = false
      //     this.text = '发送验证码'
      //     clearInterval(this.timer)
      //   }
      // }, 1000)

      // setTimeout
      this.getTime()
    },
    getTimer () {
      this.time--
      this.text = this.time + 's'
      if (this.time < 1) {
        this.disabled = false
        this.text = '发送验证码'
        clearInterval(this.timer)
      }
    },
    getTime () {
      if (this.time > 0) {
        this.time--
        this.text = this.time + 's'
        setTimeout(this.getTime, 1000)
      } else {
        this.time = 0
        this.text = '发送验证码'
        this.disabled = false
      }
    }
发布了20 篇原创文章 · 获赞 6 · 访问量 646

猜你喜欢

转载自blog.csdn.net/LR13567/article/details/105415191