Programmatic event listeners

For example, if you define a timer when the page is mounted, you need to clear the timer when the page is destroyed. This looks fine. But take a closer look at the only function of this.timer is to be able to get the timer serial number in beforeDestroy, otherwise it has no use.

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

It is best if only the lifecycle hooks can access it. This isn't a serious problem, but it can be considered a clutter.

We can solve this problem by listening for page life cycle destruction with $on or $once. You can also create multiple lives in mounted

periodic function.

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)
        })
    }
}

Even if we create multiple timers at the same time, it does not affect the effect. Because they are automatically cleared programmatically after the page is destroyed.

Guess you like

Origin blog.csdn.net/qq_42931285/article/details/124396042
Recommended