老师,我自己写的购物车,为什么在购物车点增加的时候,购物车的数量不变呢
来源:11-9 Vue实现购物车-组件设计和代码演示
走去偷柿子呀
2020-06-03
总价变化是正确的,打印出来的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>
写回答
2回答
-
椒盐皮皮虾
2020-06-25
回想一下老师讲过vue的数据监听,vue对数组怎么处理监听更新视图的
00 -
双越
2020-06-03
每次添加、减少商品时,都打印一下 cartList 的内容,看 cartList 是否符合预期。
092020-08-09