vuex中state array push is not a function错误

State array push in vuex is not a function error

我在 store/localStorage 中有一个数组来保存用户的 id 和工作时间。但是 array.push 函数不起作用。

export const state = () => ({
    Total: []
})

export const mutations = {
    setTotal(state, value){
        state.Total.push(value);
    }
}

我在创建时有这个:

this.$store.commit("localStorage/setTotal", {id: this.signedInUserID, time: 0});

这是我得到的错误:

TypeError: state.Total.push 不是函数

你的状态是一个函数,returns是一个对象。您可以通过调用 state 函数访问 Total,然后像这样处理返回的对象:state().Total.push(value)

但是在 Vuex 中,您使用 Vuex.Store() 创建 store

const store = new Vuex.Store({
  state: {
    Total: []
  },
  mutations: {
    setTotal(state, value){
      this.state.Total.push(value);
    }
  }
});

如果出于测试原因要导出突变,可以通过在之前定义它们然后仍然在 Vuex 存储中分配它们来实现。