使用 Vuex getter 从数组中获取对象 [英] Get object from array with Vuex getter
问题描述
我有一个数组状态.在 getter 中,我对其进行过滤并返回一个与另一个状态匹配的对象,如下所示:
I have a piece of state that is an array. In a getter I filter it and return an object which matches another piece of state, like this:
selectedItem: state => {
return state.items.filter(
item => item.id == state.selectedId
);
},
然而,filter()
返回一个数组,在这种情况下,它给了我一个包含 ONE 对象的数组,即带有 selectedId
的项目.我可以添加 [0]
来访问数组中的第一个对象,但这是一个非常丑陋的技巧.有没有其他方法可以确保在 Vuex getter 中过滤时得到的是对象而不是数组?
However, filter()
returns an array, which in this case gives me an array with ONE object, the item with the selectedId
. I can add [0]
to access this first object in the array, but that's a really ugly hack. Is there any other way to make sure I get an object and not an array when filtering in a Vuex getter?
推荐答案
您可以改用 find
方法.如果找不到匹配的对象,它将返回一个对象或 undefined
You can use find
method instead. It will return an object or undefined
if can't find matching object
selectedItem: state => {
return state.items.find(
item => item.id == state.selectedId
);
},
这篇关于使用 Vuex getter 从数组中获取对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!