我目前正在开发一个库存应用程序,我正在尝试在我拥有的 baseCard 组件上显示 boxID 和该盒子内的元素数量制作。
我制作的计算属性boxCards
需要以这种格式吐出数据
[{title: '', amount: null}]
因此可以将其推送到每个 baseCard
元素上。
目前,我的计算属性为我提供了标题,但我无法弄清楚如何获取每个盒子内的项目数量。
boxesInLocation 返回此数组:["", "Box 1", "Box 4", "Box 4"]
这很棒,但现在我需要计算每个框在该区域出现的次数,然后将其推送到 amount: 点中的 reshapeItems
函数.
这只是我需要使用的一个简单的reduce方法吗?因为我只能在计算数组长度时才能实际生成一个数字。
此外,仅减少数组不会将数字吐出到 reshapeItem
的每个单独实例
关于我可以在这里做什么有什么想法吗?
干杯!
App.Vue 数据:
data(){
userData: {
items: [
{
itemName: 'test book',
category: 'Books',
box: 'Box 3',
location: 'Kitchen',
},
{
itemName: 'test book 2',
category: 'Books',
box: 'Box 3',
location: 'Kitchen',
},
{
itemName: 'test book 3',
category: 'Books',
box: '',
location: 'Basement',
},
{
itemName: 'test record',
category: 'Records',
box: 'Box 1',
location: 'Basement',
},
{
itemName: 'test record 2',
category: 'Records',
box: 'Box 4',
location: 'Basement',
},
{
itemName: 'test furniture',
category: 'Furniture',
box: 'Box 2',
location: 'Garage',
},
{
itemName: 'test movie 1',
category: 'Movies',
box: 'Box 2',
location: 'Garage',
},
{
itemName: 'test movie 2',
category: 'Movies',
box: 'Box 2',
location: 'Garage',
},
{
itemName: 'test movie 3',
category: 'Movies',
box: 'Box 2',
location: 'Garage',
},
{
itemName: 'test Comicbook',
category: 'Movies',
box: 'Box 4',
location: 'Basement',
},
],
boxes: [
{ name: 'Box 1', location: 'Basement' },
{ name: 'Box 2', location: 'Garage' },
{ name: 'Box 3', location: 'Kitchen' },
{ name: 'Box 4', location: 'Basement' },
],
}
页面组件
data() {
return {
items: this.userData.items,
boxes: this.userData.boxes,
}
},
computed: {
boxCards() {
const filteredItems = this.items.filter((item) => item.location === 'Basement')
const itemsInBoxes = filteredItems.map((filteredItem) => {
return filteredItem.box
})
const filteredBoxes = this.boxes.filter((box) => box.location === 'Basement')
const reshapedBoxes = filteredBoxes.map((filteredBox) => {
return { boxID: `${filteredBox.name}`, amount: 100 }
})
return reshapedBoxes
},
最佳答案
您可以计算 this.items 数组中与相关框具有相同框名称的项目:
return this.boxes
.filter((box) => box.location === 'Basement')
.map((box) => ({
boxId: `${box.name}`,
amount: this.items.filter(item => item.box === box.name).length
}));
关于javascript - 如何使用reduce将信息传递给基础组件?/在VueJS中使用计算的props获取正确的数据传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66499719/