为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

繁星淼淼 2023-03-24 14:14:41
所以我有一个名为 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 语句之外启用推送时它会加倍推送
查看完整描述

2 回答

?
慕尼黑的夜晚无繁华

TA贡献1864条经验 获得超6个赞

请了解如何提供最小的可重现示例:https://stackoverflow.com/help/minimal-reproducible-example
最好提供一个 jsfiddle 或 codesandbox 来演示您的问题。

您不应该更改作为 a 传递的内容prop(阅读“单向流”)。

将您的orders数组作为当前组件中的本地数据对象或来自此组件的事件,并通过侦听此事件处理实际添加到父购物车的操作$emitaddToCart

假设您orders在本地数据对象中:

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++

     }

  }

}


查看完整回答
反对 回复 2023-03-24
?
幕布斯6054654

TA贡献1876条经验 获得超7个赞

检查订单中的值,如果它返回长度大于 0 的数组,则表示产品已添加,否则产品不存在。


<template>

      <div v-for="(product,index) in products" :key="index">

       <div>Name : {{ product.name }} </div>

      </div>

      <button @click="handleAdd({id:20})">Add</button>

    </template>

    

    

    props: {

      products: Array,

     orders: Array,

     }

     methods: {

       handleAdd(product){

        

          const check = this.orders.filter(item => item.id === product.id) 

          

          if(check.length === 0){

            orders.push(product)

          } else {

           // other thing

           }

        

      }

     }


查看完整回答
反对 回复 2023-03-24
  • 2 回答
  • 0 关注
  • 120 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信