无法读取未定义 VUEX 的属性“提交" [英] Cannot read property 'commit' of undefined VUEX
问题描述
请帮助我它总是说无法读取未定义的属性提交".这是我在 store.js 中的代码.
Please help me it always says Cannot read property 'commit' of undefined. Here is my code in 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:{
}
})
我在调试时遇到问题.它总是这样说'无法读取未定义的属性'提交'
I have problem it debugging. it always says like this 'Cannot read property 'commit' of undefined'
这是我的 Timer.vue 调用代码
Here is my Timer.vue code for calling
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
}
}
}
我在 Timer.vue 脚本中的代码计算和方法.我无法追踪问题出在哪里......请帮助我我在这里坚持这个.
My code in Timer.vue script computed and methods. I cannot track where the problem is... Please help me Im stuck with this here.
推荐答案
突变无法访问任何 context
.它们是原子的,也就是说它们直接与状态的一个方面一起工作.你应该让你的 startTimer
成为一个 action 提交 timer
然后开始倒计时
Mutations do not have access to any context
. They are meant to be atomic, that is they work directly with one facet of state. You should make your startTimer
an action that commits the timer
and then starts the countdown
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))
}
}
这需要通过 dispatch
而不是 commit
This would need to be called via dispatch
instead of commit
this.$store.dispatch('startTimer')
这篇关于无法读取未定义 VUEX 的属性“提交"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!