2 回答

TA貢獻1864條經(jīng)驗 獲得超6個贊
請了解如何提供最小的可重現(xiàn)示例:https://stackoverflow.com/help/minimal-reproducible-example
最好提供一個 jsfiddle 或 codesandbox 來演示您的問題。
您不應該更改作為 a 傳遞的內(nèi)容prop
(閱讀“單向流”)。
將您的orders
數(shù)組作為當前組件中的本地數(shù)據(jù)對象或來自此組件的事件,并通過偵聽此事件處理實際添加到父購物車的操作$emit
。addToCart
假設您orders
在本地數(shù)據(jù)對象中:
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++
}
}
}

TA貢獻1876條經(jīng)驗 獲得超7個贊
檢查訂單中的值,如果它返回長度大于 0 的數(shù)組,則表示產(chǎn)品已添加,否則產(chǎn)品不存在。
<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
}
}
}
添加回答
舉報