我可以在 Vuex 中更改和提交 settimeout 函数内的状态吗?

Can I change and commit the state inside settimeout function in Vuex?

form(@submit.prevent="onSubmit")
   input(type="text" v-model="platform" placeholder="Add platform name...")
   input(type="submit" value="Submit" class="button" @click="clicked = true")
   button(type="button" value="Cancel" class="btn" @click="cancelNew") Cancel      
      h3(v-if="clicked")  Thank you for adding a new platform 
         span {{ countdown }} 

这是我的模板,当用户提交表单时,我想使用 setTimeout 函数从 3 倒数并在 3 秒后提交。

如果我这样做了,就可以了;

data() {
  return {
    countdown: 3,
    platform: ""
  }
},
methods: {
  countDownTimer() {
    setTimeout(() => {
      this.countdown -= 1
      this.countDownTimer()
    }, 1000)
  },
  onSubmit() {
    let newplatform = {
      name: this.platform
    }
    this.addPlatform(newplatform)
    this.platform = ' ' 
    this.countDownTimer()
  }
}

但是我还有 3 个表单,我不想重复代码。所以想在店里放个倒计时,

countDownTimer({commit}) {
  setTimeout(() => {
    countdown = state.countdown
    countdown -= 1
    commit('COUNTDOWN', countdown)
    this.countDownTimer()
  }, 1000)
}

然后像

一样改变它
COUNTDOWN(state, countdown) {
  state.countdown = countdown
}

这不起作用,我不确定如果我能够更改状态,请在 settimeout 函数内提交更改?有没有更好的方法可以实现这个?

问题:

  1. 递归 setTimeout 没有停止。
  2. 倒计时器未重置。
  3. 使用setInterval(和clearInterval)代替递归setTimeout
  4. 对于包括 setTimeout 在内的异步逻辑,使用操作而不是突变。
  5. 从上下文对象中包含 state(你得到 commit),否则它将是未定义的。

试试这个:

actions: {
  countDownTimer({ state, commit, dispatch }) {  // state, commit, dispatch
    commit('RESET');
    const interval = setInterval(() => {         // Use `setInterval` and store it
      commit('COUNTDOWN');
      if (state.countdown === 0) {
        clearInterval(interval);                 // Clear the interval
        dispatch('updateDatabase');              // Call another action
      }
    }, 1000)
  }
}
mutations: {
  RESET(state) {
    state.countdown = 3;
  },
  COUNTDOWN(state) {
    state.countdown--;
  }
}