程序化的事件监听器

比如,在页面挂载时定义计时器,需要在页面销毁时清除定时器。这看起来没什么问题。但仔细一看 this.timer 唯一的作用只是为了能够在beforeDestroy 内取到计时器序号,除此之外没有任何用处。

export default {
    
    
    mounted() {
    
    
        this.timer = setInterval(() => {
    
    
            console.log(Date.now())
        }, 1000)
    },
    beforeDestroy() {
    
    
        clearInterval(this.timer)
    }
}

如果可以的话最好只有生命周期钩子可以访问到它。这并不算严重的问题,但是它可以被视为杂物。

我们可以通过 $on 或 $once 监听页面生命周期销毁来解决这个问题。还可以在mounted中创建多个生命

周期函数。

export default {
    
    
    mounted() {
    
    
        this.creatInterval('hello')
        this.creatInterval('world')
    },
    creatInterval(msg) {
    
    
        let timer = setInterval(() => {
    
    
            console.log(msg)
        }, 1000)
        this.$once('hook:beforeDestroy', function() {
    
    
            clearInterval(timer)
        })
    }
}

即使我们同时创建多个计时器,也不影响效果。因为它们会在页面销毁后程序化的自主清除。

猜你喜欢

转载自blog.csdn.net/qq_42931285/article/details/124396042