如何在方法 VueJs 中循环遍历数据数组

所以我有一个名为 products 的数据数组,我将它传递给 props 中的组件,然后使用 v-for order 将其显示在该组件内,当我单击一个按钮时,它会接受该命令并将其推送在另一个名为 orders 的数组中;现在我希望只有在它没有被推送之前才能推送它,否则只是增加数量这里是我的代码来帮助:


<template>

  <div v-for="product in products">{{ product.name }}</div>

</template>


我想说的是,如果 product.id = order.id 不推其他数量++;


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);

        }

      }

      

我尝试了但它一直给我 undefined 我认为它正在工作但它需要初始推送因为它一直说订单的长度为零所以没有推送,当我在 if 语句之外启用推送时它会加倍推送


繁星淼淼
浏览 121回答 2
2回答

慕尼黑的夜晚无繁华

请了解如何提供最小的可重现示例:https://stackoverflow.com/help/minimal-reproducible-example最好提供一个 jsfiddle 或 codesandbox 来演示您的问题。您不应该更改作为 a 传递的内容prop(阅读“单向流”)。将您的orders数组作为当前组件中的本地数据对象或来自此组件的事件,并通过侦听此事件处理实际添加到父购物车的操作$emit。addToCart假设您orders在本地数据对象中:data() {&nbsp; &nbsp;return {&nbsp; &nbsp; &nbsp;orders: [&nbsp; &nbsp; &nbsp; &nbsp;{ id: 'exists', quantity: 1 }&nbsp; &nbsp; &nbsp;]&nbsp; &nbsp;}},methods: {&nbsp; addToCart(product) {&nbsp; &nbsp; &nbsp;let exists = this.orders.find(p => p.id == product.id)&nbsp; &nbsp; &nbsp;if(exists == -1) { // doesn't exists yet&nbsp; &nbsp; &nbsp; &nbsp;this.orders.push(product)&nbsp; &nbsp; &nbsp;} else {&nbsp; &nbsp; &nbsp; &nbsp;this.orders[exists].quantity++&nbsp; &nbsp; &nbsp;}&nbsp; }}

幕布斯6054654

检查订单中的值,如果它返回长度大于 0 的数组,则表示产品已添加,否则产品不存在。<template>&nbsp; &nbsp; &nbsp; <div v-for="(product,index) in products" :key="index">&nbsp; &nbsp; &nbsp; &nbsp;<div>Name : {{ product.name }} </div>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; <button @click="handleAdd({id:20})">Add</button>&nbsp; &nbsp; </template>&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; props: {&nbsp; &nbsp; &nbsp; products: Array,&nbsp; &nbsp; &nbsp;orders: Array,&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;methods: {&nbsp; &nbsp; &nbsp; &nbsp;handleAdd(product){&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; const check = this.orders.filter(item => item.id === product.id)&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(check.length === 0){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; orders.push(product)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// other thing&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript