如何解决如何使用 reduce 将信息传递给基础组件? / 在 VueJS 中通过计算道具获取正确的数据
我目前正在开发一个库存应用程序,我正在尝试在我拥有的 baseCard 组件上显示 BoxID 和盒子内的物品数量制作。
我做的计算属性BoxCards
需要以这种格式吐出数据
[{title: '',amount: null}]
以便可以将其推送到每个 baseCard
元素上。
目前我的计算属性给了我标题,但我不知道如何获取每个框内的项目数量。
BoxesInLocation 返回这个数组:["","Box 1","Box 4","Box 4"]
这很好,但现在我需要计算每个框在该区域出现的次数,然后将其推送到 amount: 位置的 reshapedItems
函数。 >
这只是我需要使用的一个简单的reduce方法吗?因为在计算数组的长度时,我只能实际生成一个数字。
此外,仅仅减少数组不会将数量吐出到 reshapedItem
的每个单独实例
对我在这里可以做什么有什么想法吗?
干杯!
App.Vue 数据:
data(){
userData: {
items: [
{
itemName: 'test book',category: 'Books',Box: 'Box 3',location: 'Kitchen',},{
itemName: 'test book 2',{
itemName: 'test book 3',Box: '',location: 'Basement',{
itemName: 'test record',category: 'Records',Box: 'Box 1',{
itemName: 'test record 2',Box: 'Box 4',{
itemName: 'test furniture',category: 'Furniture',Box: 'Box 2',location: 'Garage',{
itemName: 'test movie 1',category: 'Movies',{
itemName: 'test movie 2',{
itemName: 'test movie 3',{
itemName: 'test Comicbook',],Boxes: [
{ name: 'Box 1',location: 'Basement' },{ name: 'Box 2',location: 'Garage' },{ name: 'Box 3',location: 'Kitchen' },{ name: 'Box 4',}
页面组件
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
}));
,
您需要在 Map
中保存每个 box
的出现次数,然后获取您正在执行的第二个循环中每个出现的次数:
const userData = {
items: [
{ itemName: 'test book',category: 'Books',box: 'Box 3',location: 'Kitchen' },{ itemName: 'test book 2',{ itemName: 'test book 3',box: '',location: 'Basement' },{ itemName: 'test record',category: 'Records',box: 'Box 1',{ itemName: 'test record 2',box: 'Box 4',{ itemName: 'test furniture',category: 'Furniture',box: 'Box 2',location: 'Garage' },{ itemName: 'test movie 1',category: 'Movies',{ itemName: 'test movie 2',{ itemName: 'test movie 3',{ itemName: 'test Comicbook',],boxes: [
{ name: 'Box 1',{ name: 'Box 2',{ name: 'Box 3',{ name: 'Box 4',]
};
function boxCards() {
const boxesCount = userData.items
.reduce((quantity,{box}) =>
quantity.set(box,1 + (quantity.get(box) || 0)),new Map);
return userData.boxes
.filter(box =>
box.location === 'Basement'
)
.map(filteredBox =>
({ boxID: filteredBox.name,amount: boxesCount.get(filteredBox.name) })
);
}
console.log( boxCards() );
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。