鍍金池/ 問答/HTML/ vuex 如何清空setInterval

vuex 如何清空setInterval

緣由:
在子路由里有個setInterval,一直不停調(diào)用某個接口,但是回到其他頁面或者父路由頁面就要清空這個setInterval;
在這個子組件中定義setInterval為timer,當(dāng)然可以清空,不過在其他頁面中是找不到這個timer的,
所以想到用vuex處理;

    mounted(){
        this.init();
        // this.$store.dispatch('fetchPageList');
    },
    methods:{
        backTrack(){
            this.$store.commit('showBg',false);
            // clearInterval(this.$store.commit('changeKeepInter',undefined));
        },
        init(){
            let _time = new Date().getTime();
            this.$http.get('https://xx?appkey=' + this.appId + '&os=' + this.plat + '&timestamp=' + _time,{
                headers: {
                    'Content-Type': 'application/json;charset=UTF-8;'
                }
            })
            .then((data)=>{
                this.$store.commit('changeKeepInter',setInterval(function(){
                    console.log('打印');
                    // to do
                },2000));
            },(err)=>{

            })

        }
    }

如上,不知道怎么clearInterval 這個timer(changeKeepInter的值)?剛接觸vuex,有不了解的地方,請各位大神指教!

因?yàn)槲倚枰谄渌撁嬷杏玫竭@個setInterval,需要在其他頁面中手動清空,請問這個該怎么處理?

回答
編輯回答
笨笨噠

1.你應(yīng)該在當(dāng)前頁面吧setInterval返回的id存到store里面
2.在另外一個頁面里通過store拿到這個id,然后直接在這個頁面里調(diào)用clearInterval,同時把store里的id清空

2018年8月13日 09:47
編輯回答
瘋子范

在你路由destroyed的時候清掉唄。

export default {
    data() {
        return {
            someTimer: null
        }
    },
    methods: {
        someFunc() {
            this.someTimer = setInterval(() => {}, 2000);
        }
    },
    destroyed() {
        this.someTimer && window.clearInterval(this.someTimer);
    }
}
2017年1月29日 21:01
編輯回答
別瞎鬧

既然你回到其他頁面或者父路由頁面就要清空這個setInterval
那么這個定時器就應(yīng)該在它所在組件的生命周期內(nèi)自生自滅。組件 destroyed 的時候清除就好了。

2017年6月5日 08:13
編輯回答
淺淺

路由導(dǎo)航鉤子
beforeRouteLeave(to,from,next){

//清除代碼...
next();

}

2017年12月24日 15:56