两种清除setInterval的方式:this
方案一:spa
data() { return { timer: null // 定时器名称 } }, mouted() { this.timer = (() => { // 某些操做 }, 1000) }, beforeDestroy() { clearInterval(this.timer); this.timer = null; }
方案二(官方推荐):经过$once事件侦听器器在定义完定时器以后的位置来清除定时器。code
方案一有两个潜在的问题:blog
timer
,若是能够的话最好只有生命周期钩子能够访问到它。这并不算严重的问题,可是它能够被视为杂物。mounted() { const timer = setInterval(() =>{ // 某些定时器操做 }, 500); // 经过$once来监听定时器,在beforeDestroy钩子能够被清除。 this.$once('hook:beforeDestroy', () => { clearInterval(timer); }) }