如何在 Vuex 中清除间隔
Posted
技术标签:
【中文标题】如何在 Vuex 中清除间隔【英文标题】:How to ClearInterval in Vuex 【发布时间】:2020-11-03 23:58:46 【问题描述】:我正在尝试清除我的 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:
);
【问题讨论】:
在这种情况下,您是不是误用了clearInterval(this.myCounterInterval);
,而您的意思是clearInterval(state.myCounterInterval);
【参考方案1】:
你可以这样做
stopCounter (state)
state.myCounterInterval = null
...
,
这样设置间隔
行动
startCounter ( state, commit )
commit("setCounter")
变异
setCounter (state)
state.count = 0;
state.myCounterInterval = setInterval(() =>
your logic
, 1000))
,
【讨论】:
谢谢,不过好像也不起作用,可能是我设置间隔的方式? 我无法在突变中执行我的逻辑,因为我需要执行 commit("countDown");在 setInterval 在区间内从 countDown 进行所有突变有什么问题?【参考方案2】:您需要删除此分配:
this.myCounterInterval = commit("setCounter", setInterval(() =>
,然后提交:
commit("setCounter", setInterval(() =>
“setCounter”突变将您的计数器分配给 state.count:
setCounter (state, newCount)
state.count = newCount;
,然后你可以删除这个区间:
stopCounter (state)
clearInterval(state.count);
这个适合我
【讨论】:
以上是关于如何在 Vuex 中清除间隔的主要内容,如果未能解决你的问题,请参考以下文章