美文网首页
vue中beforeDestroy清理定时器的最佳方式

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

作者: MC桥默 | 来源:发表于2022-02-14 22:12 被阅读0次

    前言

    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清理定时器的最佳方式

          本文链接:https://www.haomeiwen.com/subject/qjghlrtx.html