Как очистить интервал в Vuex - PullRequest
0 голосов
/ 14 июля 2020

Я пытаюсь очистить интервал в моем хранилище 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: {}
});

1 Ответ

1 голос
/ 14 июля 2020

Вы можете сделать что-то вроде этого

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

Установить интервал примерно так

действия

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

мутации

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