总价变化是正确的,打印出来的quantity值也是对的,但页面显示的值不对。
例如点击了商品a之后,不管点击“添加”按钮多少次,商品a数量显示都是1,但如果这个时候点击了商品b,商品a的数量就会变成对的
我是分了三个文件:商品列表production、购物车列表cart、总容器index,用的是父子组件间传值的方法。
下面是index的代码
<template>
<div>
<production @addToCart="addToCart" :list="productionList"></production>
<hr />
<cart
@addToCart="addToCart"
@delFromCart="delFromCart"
:list="cartList"
></cart>
<hr />
<div>总价:{{ totalPrice }}</div>
</div>
</template>
<script>
import production from './production'
import cart from './cart'
export default {
components: {
production,
cart,
},
data() {
return {
productionList: [
{
name: '商品a',
id: '1',
price: 100,
},
{
name: '商品b',
id: '2',
price: 200,
},
{
name: '商品c',
id: '3',
price: 300,
},
],
cartList: [],
totalPrice: 0,
}
},
methods: {
addToCart(item) {
const shopIndex = this.cartList.indexOf(item)
if (shopIndex === -1) {
item.quantity = 1
this.cartList.push(item)
} else {
this.cartList[shopIndex].quantity += 1
}
this.totalPrice += item.price
},
delFromCart(item) {
const shopIndex = this.cartList.indexOf(item)
this.cartList[shopIndex].quantity -= 1
if (this.cartList[shopIndex].quantity === 0) {
this.cartList.splice(shopIndex, 1)
}
this.totalPrice -= item.price
},
},
}
</script>
下面是cart的代码
<template>
<div>
<div class="cart-container" v-for="item in list" :key="item.id">
<div class="cart-info">
<span>{{ item.name }}</span>
<span>{{ item.quantity }}</span>
</div>
<div class="cart-btn">
<button @click="addToCart(item)">增加</button>
<button @click="delFromCart(item)">减少</button>
</div>
</div>
</div>
</template>
<script>
export default {
props: {
list: {
type: Array,
default() {
return []
},
},
},
methods: {
addToCart(item) {
this.$emit('addToCart', item)
},
delFromCart(item) {
this.$emit('delFromCart', item)
},
},
}
</script>
<style>
.cart-container {
width: 300px;
display: flex;
justify-content: space-between;
margin: 10px;
}
.cart-info {
width: 100px;
display: flex;
justify-content: space-between;
}
.cart-btn {
width: 100px;
display: flex;
justify-content: space-between;
}
</style>
下面是production的代码
<template>
<div>
<div class="production-container" v-for="item in list" :key="item.id">
<div class="production-info">
<span>{{ item.name }}</span>
<span>{{ item.price }}</span>
</div>
<button @click="addToCart(item)">加入购物车</button>
</div>
</div>
</template>
<script>
export default {
props: {
list: {
type: Array,
default() {
return []
},
},
},
methods: {
addToCart(item) {
this.$emit('addToCart', item)
},
},
}
</script>
<style>
.production-container {
width: 300px;
display: flex;
justify-content: space-between;
margin: 10px;
}
.production-info {
width: 100px;
display: flex;
justify-content: space-between;
}
</style>