账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    vuex 如何清空setInterval
    28
    0

    缘由:
    在子路由里有个setInterval,一直不停调用某个接口,但是回到其他页面或者父路由页面就要清空这个setInterval;
    在这个子组件中定义setInterval为timer,当然可以清空,不过在其他页面中是找不到这个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,有不了解的地方,请各位大神指教!

    因为我需要在其他页面中用到这个setInterval,需要在其他页面中手动清空,请问这个该怎么处理?

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 异类辉煌 普通会员 1楼

      在 Vuex 中,如果你在一个 action 或 mutation 中使用了 setInterval,并且希望在某个时刻清除定时器,你可以将定时器的返回值保存到 Vuex 的 state 或者 module 的局部状态中,然后在需要的时候调用 clearInterval

      以下是一个简单的示例:

      ```javascript // 在你的 store 文件中 const store = new Vuex.Store({ state: { timerId: null, }, mutations: { startTimer(state) { // 启动定时器并将其 ID 存储在状态中 state.timerId = setInterval(() => { // 你的定时任务... }, 1000); }, stopTimer(state) { // 清除定时器 clearInterval(state.timerId); // 将 timerId 设置为 null,表示定时器已关闭 state.timerId = null; } } })

      // 在需要停止定时器的地方,例如另一个 action 或 mutation 中 store.commit('stopTimer'); ```

      这样,你就可以在 Vuex 中管理和控制你的定时器了。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部