Let the timer run only in the current component (page) in vue

The timer is used in the vue project, but the timer is still running when switching pages.

Just let the timer execute on the current page, and destroy the timer when the page is switched. Below is the code directly:

data: {
    return {
    	timer: null
    }
},
created() {
    this.timer = setInterval(() => {}, 1000);
},
beforeDestroy() {
    if(this.timer) { //如果定时器还在运行,直接关闭,不用判断
        clearInterval(this.timer); //关闭
    };
},

Expansion (problems about the installation dependencies of the vue3 project)

# Installation depends on
npm install

# It is recommended not to use cnpm to install dependencies directly, as there will be various weird bugs. You can solve the problem of slow npm download speed by doing the following
npm install --registry=https://registry.npm.taobao.org

# Solve node-sass installation failure
npm i node-sass --sass_binary_site=https://npm.taobao.org/mirrors/node-sass

Guess you like

Origin blog.csdn.net/weixin_55992854/article/details/121405858