Vuex商店,为什么要添加到数组中以最后一个条目覆盖商店中的所有值?

时间:2018-07-12 15:13:52

标签: javascript vue.js vuejs2 vuex vuex-modules

我正在使用vuex-typescript。这是一个商店模块:

import { getStoreAccessors } from "vuex-typescript";
import Vue from "vue";
import store from "../../store";
import { ActionContext } from "vuex";
class State {
  history: Array<object>;
}

const state: State = {
  history: [],
};

export const history_ = {
  namespaced: true,
  getters: {

    history: (state: State) => {

      return state.history;
    },

  },
  mutations: {

    addToHistory (state: State, someob: any) {

      state.history.push(someob);

    },

    resetState: (s: State) => {
      const initial = state;
      Object.keys(initial).forEach(key => { s[key] = initial[key]; });
    },
  },

  actions: {
    addToHistory(context: ActionContext<State, any>, someob: any) {
      commitAddToHistory(store, someob);
    }

  }

const { commit, read, dispatch } =
  getStoreAccessors<State, any>("history_");
const mutations = history_.mutations;
const getters = history_.getters;
const actions = history_.actions;

export const commitResetState = commit(mutations.resetState);
export const commitAddToHistory = commit(mutations.addToHistory);
export const getHistory = read(getters.history);
export const dispatchAddToSearchHistory = dispatch(actions.addToHistory);

现在,如果调用dispatchAddToSearchHistorycommitAddToHistory,则总是相同,所有值都将被覆盖。例如,如果我添加一个要存储的元素,则它看起来像这样:

store = [
  {
    a: 1
  }
]

现在,当我添加另一个对象{b: 2}时,存储就会变成

store = [
  {
    b: 2
  },
  {
    b: 2
  }
]

所有值都由最后一个条目改写。例如,如果我尝试添加{c:3},则存储看起来像(依此类推):

store = [
  {
    c: 3
  },
  {
    c: 3
  },
  {
    c: 3
  }
]

1 个答案:

答案 0 :(得分:0)

.... hmmmm,我想您可能每次都发送相同的对象

请尝试此突变

addToHistory (state: State, someob: any) {
  state.history.push({...someob});
},

或此操作

addToHistory(context: ActionContext<State, any>, someob: any) {
  commitAddToHistory(store, {...someob});
}

此操作使用散布运算符克隆对象。这样,您添加的每个项目都会成为新对象。