vue中beforeDestroy清理定时器的最佳方式

前言

vue项目中,很多人写定时器时,会把定时器timer定义在data里面,等到周期函数beforeDestroy时,使用clearInterval(timer)来销毁。实际上定时器timer没必要定义在data里面,这样会增加内存消耗。我们可以把定时器定义在mounted里面,然后使用hook来监听beforeDestroy,当beforeDestroy触发时,销毁定时器。这样定时器和清理定时器达到了成对出现而且离得很近的效果。代码如下。

mounted() {
            let currentTimer = setInterval(() => {
                this.time = dayjs().format('YYYY-MM-DD HH:mm:ss')
            }, 1000)
            this.$once('hook:beforeDestroy', () => {
                clearInterval(currentTimer)
                currentTimer = null
                console.log('全都销毁了');
            })
        },

你可能感兴趣的:(vue中beforeDestroy清理定时器的最佳方式)