我的vuex商店中有一个名为case的数组。
当我更新数组中现有项目中的几个字段时,我想用新内容更新数组。
我以为我可以在变异中做类似的事情,但无法正常工作并得到错误typeError: undefined is not an object (evaluating 'state.objects.find')
-
EDIT_CASE (state, payload) {
const item = state.objects.find(item => item.id === payload.recordId);
Object.assign(item, payload.case_status);
Run Code Online (Sandbox Code Playgroud)
我的数组如下:
[
{
"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"
}
]
Run Code Online (Sandbox Code Playgroud)
我还认为,根据我所读的内容,Vue不会观察到数组内的变化,因此这可能是我走错了路,需要删除然后重新添加数组项吗?
基本上,我有一个列表,我对后端进行了更改,现在我希望该列表反映我通过更新案例状态所做的更改,任何人都可以帮忙吗?
Max*_*nev 15
您的示例没有数组问题,因为您尝试更改对象属性-而不是数组元素引用。问题出在Object.assign(item, payload.case_status);
-您应该提供一个对象而不仅仅是一个字段。(您还说过,名为cases
example的数组具有objects
,也许这也是个问题);
所以这应该工作:
EDIT_CASE (state, payload) {
const item = state.objects.find(item => item.id === payload.recordId);
Object.assign(item, payload);
}
Run Code Online (Sandbox Code Playgroud)
错误:
未定义不是对象
我认为,这与之相关,Object.assign
因为您将字段传递给了未定义的字段。
PS有一个小例子可以帮助您了解何时出现阵列问题以及何时一切正常。查看代码注释:)
EDIT_CASE (state, payload) {
const item = state.objects.find(item => item.id === payload.recordId);
Object.assign(item, payload);
}
Run Code Online (Sandbox Code Playgroud)
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" });
}
}
})
Run Code Online (Sandbox Code Playgroud)
JavaScript(不是Vue特有的)无法检测直接通过索引设置Array项的值arr[3] = 'stop';
,也无法检测从对象添加新键或删除现有键。您必须定义商店的初始状态,例如
const store = new Vuex.Store({
state: {
objects: []
},
mutations: {
EDIT_CASE (state, payload) {
const index = state.objects.findIndex(item => item.id === payload.id);
if (index !== -1) state.objects.splice(index, 1, payload);
}
}
})
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9322 次 |
最近记录: |