如何循环遍历方法 VueJs 中的数据数组 [英] How to loop through an array of data inside methods VueJs
问题描述
所以我有一个名为 products 的数据数组,我将它传递给我在 props 中的组件,然后使用 v-for order 命令将其显示在该组件内,当我单击一个按钮时,它会采用该顺序并将其推入另一个名为 orders 的数组中;现在我希望只有在它没有被推送的情况下才能推送它,否则只是增加数量这是我的帮助代码:
so I have an array of data called products and i'm passing it to my component in props, then using v-for order in orders to display it inside that component, when I click on a button, it takes that order and push it inside another array called orders; now I want to be able to push it only if it wasn't pushed before other wise just increment the quantity here's my code to help:
<template>
<div v-for="product in products">{{ product.name }}</div>
</template>
我想说的是如果product.id = order.id 不推其他数量++;
what I wanna say is if product.id = order.id don't push other quantity++;
props: {
products: Array,
orders: Array,
}
methods: {
for(let i=0; i<this.orders.length; i++){
if(product.id != this.orders[i].id || this.orders.length == 0){
console.log('sure what the hell');
console.log(this.orders[i].id);
this.orders.push(product);
} else {
console.log('baught it before');
console.log(this.orders[i].id);
}
}
我尝试过,但它一直给我未定义我认为它正在工作,但它需要初始推送,因为它一直说订单长度为零,因此没有推送任何内容,当我在 if 语句之外启用推送时,它会将推送加倍
I try it but it keeps giving me undefined I think it is working but it needs an initial push because it keeps saying the length of orders is zero so nothing is pushed, when I enable a push outside of the if statement it doubles the pushes
推荐答案
请了解如何提供最小的可重现示例:https://stackoverflow.com/help/minimal-reproducible-example
理想情况下,提供一个 jsfiddle 或代码沙盒来展示您的问题.
Please learn how to provide a minimal reproducible example: https://stackoverflow.com/help/minimal-reproducible-example
Ideally provide a jsfiddle or codesandbox demonstrating your problem.
您不应更改作为 prop
传入的内容(阅读单向流程").
You shouldn't change something that was passed in as a prop
(read up on "one way flow").
要么将您的 orders
数组作为当前组件中的本地数据对象,要么$emit
来自该组件的 addToCart
事件并处理通过侦听此事件实际添加到父级中的购物车.
Either have your orders
array as a local data object in the current component or $emit
an addToCart
event from this component and handle the actual adding to cart in the parent by listening to this event.
假设您的 orders
在本地数据对象中:
Assuming your orders
are in the local data object:
data() {
return {
orders: [
{ id: 'exists', quantity: 1 }
]
}
},
methods: {
addToCart(product) {
let exists = this.orders.find(p => p.id == product.id)
if(exists == -1) { // doesn't exists yet
this.orders.push(product)
} else {
this.orders[exists].quantity++
}
}
}
这篇关于如何循环遍历方法 VueJs 中的数据数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!