如何在 Vuex 中清除间隔

How to ClearInterval in Vuex

我正在尝试清除我的 vuex 存储中的一个间隔,但它不起作用。

在 startCounter 中,我检查我的计数是否等于 100 以清除 stopCounter 中的间隔

clearInterval(this.myCounterInterval);

这是我的代码,谢谢。

import Vue from "vue";
import Vuex from "vuex";
import videos from "@/models/videos";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    count: 0,
    totalTime: 20,
    myCounterInterval: 0,
    visible: false,
    show: false,
    videos: {
      type: Array,
      default: () => videos
    }
  },
  mutations: {
    visibleProgressBar (state) {
      state.visible = true;
    },
    invisibleProgressBar (state) {
      state.visible = false;
    },
    showModal (state) {
      state.show = true;
    },
    hideModal (state) {
      state.show = false;
    },
    countDown (state) {
      if(state.totalTime >= 1) {
        state.totalTime--;
        state.count += 5;
      } else {
        state.totalTime = 0;
        state.count = 0;
        return;
      }
    },
    setCounter (state, newCount) {
      state.count = newCount;
    },
    stopCounter (state) {
      clearInterval(this.myCounterInterval);
      state.count = 0;
    },
    setVideos (state) {
      state.videos;
    }
  },
  actions: {
    startCounter ({ state, commit }) {

      this.myCounterInterval = commit("setCounter", setInterval(() => {
        commit("countDown");

        if(state.count === 100) {
          commit("stopCounter");
        }
      }, 1000));
    },
    stopCounter ({ commit }) {
      commit("stopCounter");
    },
    showProgressBar ({ commit }) {
      commit("visibleProgressBar");
    },
    hideProgressBar ({ commit }) {
      commit("invisibleProgressBar");
    },
    showModal ({ commit }) {
      commit("showModal");
    },
    hideModal ({ commit }) {
      commit("hideModal");
    },
    getVideos ({ commit }) {
      commit("setVideos");
    }
  },
  modules: {}
});

你可以这样做

stopCounter (state) {
    state.myCounterInterval = null
    ...
},

像这样设置间隔

动作

startCounter ({ state, commit }) {
      commit("setCounter")
}

突变

setCounter (state) {
   state.count = 0;
   state.myCounterInterval = setInterval(() => {
      your logic
   }, 1000))
},

您需要删除此作业:

this.myCounterInterval = commit("setCounter", setInterval(() => {

,然后提交:

commit("setCounter", setInterval(() => {

"setCounter" 突变将你的计数器分配给 state.count:

setCounter (state, newCount) {
  state.count = newCount;
}

,然后可以删除这个区间:

stopCounter (state) {
  clearInterval(state.count);
}

这个适合我