首页 > 解决方案 > 当一项有一些变化时更新vuex数组的状态

问题描述

我的 vuex 商店中有一个名为 case 的数组。

当我更新数组中现有项目中的几个字段时,我想用新内容更新数组。

我以为我可以在我的突变中做这样的事情,但不起作用并得到错误typeError: undefined is not an object (evaluating 'state.objects.find')-</p>

EDIT_CASE (state, payload) {
    const item = state.objects.find(item => item.id === payload.recordId);
Object.assign(item, payload.case_status);

我的数组如下:

[
    {
        "case_name": "Laptop not working",
        "case_status": "live",
        "case_summary": "This is some summary content",
        "createdBy": "zippy",
        "createdDate": "2018-06-21T15:20:22.932Z",
        "id": "-LFXvk9yY5c-O8yIdf8k"
    },
    {
        "case_name": "Something else",
        "case_status": "live",
        "case_summary": "This is some summary content",
        "createdBy": "zippy",
        "createdDate": "2018-06-21T15:20:22.932Z",
        "id": "-STVvk9yY5c-O3yiTy8k"
    }
]

我还认为,从我读过的内容来看,Vue 没有观察到数组内的变化,所以我可能完全走错了路,需要删除然后重新添加数组项?

基本上我有一个列表,我对后端进行了更改,现在我希望该列表反映我通过更新案例状态所做的更改,有人可以帮忙吗?

标签: vue.jsvuejs2vuex

解决方案


您的示例没有数组问题,因为您尝试更改对象属性 - 而不是数组元素引用。问题在于Object.assign(item, payload.case_status);- 您应该提供一个对象而不仅仅是一个字段。(你也说过那个数组被调用cases但是例子有objects,也许这也是问题);

所以这应该工作:

EDIT_CASE (state, payload) {
    const item = state.objects.find(item => item.id === payload.recordId);
    Object.assign(item, payload);
}

错误:

undefined 不是对象

我认为,这与Object.assign您将字段传递给它可能是未定义的有关。

PS 有一个小例子可以帮助您了解何时出现阵列问题以及何时一切正常。见代码注释:)

new Vue({
  el: "#app",
  data: {
    todos: [
      { text: "Learn JavaScript" },
      { text: "Learn Vue" },
      { text: "Play around in JSFiddle" },
      { text: "Build something awesome" }
    ]
  },
  methods: {
    // work because object property is reactive
  	changeItemProperty() {
    	this.todos[3].text = "changedItemProperty";
    },
    // same reason, properties are reactive
    changeItemWithAssign() {
    	Object.assign(this.todos[3], { text: "changedItemWithAssign" });
    },
    // does not work, can not track changes in array
    // also this will break all attempts to change TEXT property in UI
    // because property becomes not reactive after this due to new object
    // try to changeItemProperty or  changeItemWithAssign - does not work!
    // changeItem2 will fix it :)
    changeItem() {
    	this.todos[3] = { text: "changedItem" }
    },
    // works
    changeItem2() {
    	Vue.set(this.todos, 3, { text: "changedItem2" });
    }	
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="app">
  <div v-for="todo in todos" :key="todo.text">
     {{todo.text}}
  </div>
  <button @click="changeItemProperty">changeItemProperty(works)</button>
  <button @click="changeItemWithAssign">changeItemWithAssign(works)</button>
  <button @click="changeItem">changeItem(does not work!)</button>
  <button @click="changeItem2">changeItem2(works)</button>
</div>


推荐阅读