Vuex 存储,为什么添加到数组会用最后一个条目覆盖存储中的所有值? [英] Vuex store, why adding to array overwrites all values in store with last entry?

查看:36
本文介绍了Vuex 存储,为什么添加到数组会用最后一个条目覆盖存储中的所有值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using vuex-typescript. This is one store module:

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 它总是相同的所有值都被覆盖.例如,如果我添加一个元素来存储,那么它看起来像这样:

Now if if call dispatchAddToSearchHistory or commitAddToHistory it is always the same all values get overwritten. For example if I add one element to store then it looks like this:

store = [
  {
    a: 1
  }
]

现在当我添加另一个对象 {b: 2} 商店变成

now when I add another object {b: 2} store becomes

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

所有值都由最后一个条目写入.例如,如果我尝试添加 {c:3} 然后 store 看起来像(等等):

All values are owerwritten by last entry. For example if I try to add {c:3} then store looks like (and so on):

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

推荐答案

....嗯,嗯,我想你可能每次都发送同一个对象

....hmmmm, well, I think you may be sending the same object, every time

请试试这个突变

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

或者这个动作

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

this 使用扩展运算符克隆对象.这样,您添加的每个项目都将成为新对象.

this, using the spread operator, clones the object. That way every item you add will be new object.

这篇关于Vuex 存储,为什么添加到数组会用最后一个条目覆盖存储中的所有值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆