方法一:
1、data中定义timer变量
data() { return { timer: null } }
2、在使用定时器时将定时器赋值给timer
methods: { toggleImg() { this.timer = setInterval(() => { this.currentIndex++ if (this.currentIndex === this.list.length) this.currentIndex = 0 }, 1000) } }
3、清除定时器
beforeDestroy() { clearInterval(this.timer) this.timer = null }
方法二:
在定义定时器的方法或生命周期中通过变量timer接收,然后在方法的后面销毁该定时器,这样写的好处是便于维护
methods: { toggleImg() { const timer = setInterval(() => { this.currentIndex++ if (this.currentIndex === this.list.length) this.currentIndex = 0 }, 1000) this.$once('hook:beforeDestroy', () => { clearInterval(timer) timer = null }) } }