vue验证码倒计时

有一个需求
手机号发送验证码的倒计时
一开始是想要直接通过计算属性直接return 出倒计时的值
但是出现一个问题
报错

Unexpected side effect in “xxxx“ computed property
后来发现是因为computed不可以直接改变变量的值,然后写在了watch里面

上代码

<el-button type="primary" :disabled="isSend" @click="isSend=true">{{ sendMessage }}</el-button>
computed: {
    sendMessage() {
      if (this.isSend) {
        return this.sendTimer + '秒后重新发送'
      } else {
        return '点击发送'
      }
    },
    }

在watch里监听并倒计时

  watch: {
    isSend: {
      handler(val) {
        this.sendTimer = 60
        const timeOut = setInterval(() => {
          if (this.sendTimer <= 0) {
            clearInterval(timeOut)
            this.isSend = false
          } else {
            this.sendTimer--
          }
        }, 1000)
      }
    }
  },

完成啦
效果
点击发送,开始倒计时,倒计时完成后可再次发送

上一篇:2020VUE常考-属性作用与对比


下一篇:watch和computed区别 及二者使用场景