无法读取未定义 VUEX 的属性“提交”

Pet*_*ker 4 javascript commit undefined vuex

请帮助我它总是说无法读取未定义的属性“提交”。这是我在 store.js 中的代码。

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export const store = new Vuex.Store({
  state:{
     timer: null,
     totaltime: (25 * 60)
  }, 
  mutations:{
    startTimer: (state, context) => {
    //here is the problem part I think
      state.timer = setInterval(() => context.commit('countDown'),
      1000)
    },
    countDown: state => {
      var time = state.totaltime
      if(time >= 1){
        time--
      }else{
        time = 0
      }
    },
    stopTimer: state => {
      clearInterval(state.timer)
      state.timer = null
    },
    resetTimer: state => {
      state.totaltime = (25 * 60)
      clearInterval(state.timer)
    }
  },
  getters:{
      minutes: state => {
        const minutes = Math.floor(state.totaltime / 60);
        return minutes;
      },
      seconds: (state, getters) => {
        const seconds = state.totaltime - (getters.minutes * 60);
        return seconds;
      }
  },
  actions:{


  }
})
Run Code Online (Sandbox Code Playgroud)

我有问题调试。它总是这样说'无法读取未定义的属性'提交''

这是我用于调用的 Timer.vue 代码

methods: {
      formTime(time){
        return (time < 10 ? '0' : '') + time;
      },
      startTimer(){
        this.resetButton = true
        this.$store.commit('startTimer')
      },
      stopTimer(){
        this.$store.commit('stopTimer')
      },
      resetTimer(){
        this.$store.commit('resetTimer')
      },

    },
    computed: {
      minutes(){
        var minutes = this.$store.getters.minutes;
        return this.formTime(minutes)
      },
      seconds(){
        var seconds = this.$store.getters.seconds;
        return this.formTime(seconds);
      },
      timer: {
        get(){
          return this.$store.state.timer
        }
      }
    }
Run Code Online (Sandbox Code Playgroud)

我在 Timer.vue 脚本中计算的代码和方法。我无法追踪问题出在哪里......请帮助我我在这里坚持这个。

Phi*_*hil 6

突变无法访问任何context. 它们是原子的,也就是说它们直接与状态的一个方面一起工作。你应该让你startTimer行动,承诺了timer,然后开始倒计时

mutations: {
  // add this one for setting the timer
  setTimer (state, timer) {
    state.timer = timer
  }
},
actions: {
  startTimer ({ commit }) {
    commit('stopTimer') // just a guess but you might need this
    commit('setTimer', setInterval(() => {
      commit('countDown')
    }, 1000))
  }
}
Run Code Online (Sandbox Code Playgroud)

这将需要通过调用dispatch而不是commit

this.$store.dispatch('startTimer')
Run Code Online (Sandbox Code Playgroud)