vue3中的定时器问题

写一个手机验证码登录,获取验证码会倒计时,所以用到了定时器,但是不知道要怎样清除定时器

img

img

登录成功之后会有这个报错,不断累加报错

img

代码:

img

你可以试试在组件销毁的时候清除定时器,或者在路由切换的时候去清除定时器

在Vue 3中使用定时器,可以使用setInterval()或者setTimeout()函数。为了清除定时器,需要保存定时器的ID,以便在需要时清除它。

以下是一个在Vue 3中使用setInterval()实现倒计时的示例:

在模板中,我们可以使用v-if指令判断是否需要显示倒计时,如果需要则显示倒计时,否则显示获取验证码按钮。同时,在获取验证码时调用startTimer()函数开始倒计时,倒计时结束后调用stopTimer()函数清除定时器。

<template>
  <div>
    <button v-if="!showTimer" @click="getVerificationCode()">获取验证码</button>
    <span v-else>{{ count }}秒后重新获取</span>
  </div>
</template>

<script>
export default {
  data() {
    return {
      showTimer: false,
      count: 60,
      timerId: null
    };
  },
  methods: {
    getVerificationCode() {
      // 发送验证码请求
      
      // 开始倒计时
      this.startTimer();
    },
    startTimer() {
      this.showTimer = true;
      this.timerId = setInterval(() => {
        if (this.count > 0) {
          this.count--;
        } else {
          this.stopTimer();
        }
      }, 1000);
    },
    stopTimer() {
      this.showTimer = false;
      clearInterval(this.timerId);
      this.timerId = null;
      this.count = 60;
    }
  }
};
</script>
在上面的示例中,使用setInterval()函数创建定时器,并将返回的ID存储在timerId变量中。在stopTimer()函数中,使用clearInterval()函数清除定时器。如果需要在适当的时候重新开始倒计时,可以再次调用startTimer()函数。


感觉是报错了,没有执行清除定时器, 试试在你的代码clearInterval(loop)这个上面打印个东西看看能不能打印出来

你可以在登陆成功页面跳转之前清除定时器,setinterval设置定时器,clearinterval用来清除定时器

img

在你的let loop 上面写clearInterval(loop)