亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在方法 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 關注
  • 179 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號