加入购物车
<template>
<div class="shop-container">shop
<table>
<tr>
<th>商品</th>
<th>数量</th>
<th>单价</th>
<th>金额</th>
</tr>
<tr v-for="item in goods" :key="item.id">
<td>
<input type="checkbox" @click="handleCheckClick(item)">
{{ item.name }}
</td>
<td>
<button @click="calcSingleGoodPrice(item, 0)">-</button>
<input type="text" v-model="item.number">
<button @click="calcSingleGoodPrice(item, 1)">+</button>
</td>
<td>{{ item.price }}</td>
<!-- <td>{{item.price * item.number | formatPrice}}</td> -->
<td>{{item.price * item.number?item.price * item.number:0}}</td>
</tr>
<tr>
<td colspan="4" align="right">
<span>总金额:</span>
{{ calcTotalPrice | formatPrice }} ¥
</td>
</tr>
</table>
</div>
</template>
<script>
export default {
name: "Shop",
data() {
return {
goods: [
{ id: 1, name: "牙膏", price: 13 },
{ id: 2, name: "牙刷", price: 10 },
{ id: 3, name: "沐浴露", price: 25 },
{ id: 4, name: "毛巾", price: 10 }
]
};
},
created: function() {
//如果不使用箭头函数,this的指向就不是vue的实例了
this.goods.forEach((good, index) => {
if (
typeof good.number === "undefined" &&
typeof good.checked === "undefined"
) {
this.$set(good, "number", 0);
this.$set(good, "checked", false);
}
});
},
methods: {
//点击加减按钮,计算单个商品金额
calcSingleGoodPrice(item, minusOrPlus) {
/*if (typeof item.number === 'undefined') {
this.$set(item, 'number', 0);
}*/
if (minusOrPlus === 1) {
item.number++;
} else if (minusOrPlus === 0) {
if (!!item.number) {
item.number--;
}
}
},
//处理checkbox的勾选;给数据添加勾选标识
handleCheckClick(item) {
item.checked = !item.checked;
}
},
//格式化金额显示,避免出现NaN的情况
filters: {
formatPrice(val) {
return isNaN(val) ? 0 : val;
}
},
computed: {
//只要goods里面的数据有修改,就会执行calcTotalPrice
calcTotalPrice() {
var goods = this.goods,
totalPrice = 0;
//forEach回调,第一个参数是当前循环的对象,第二个参数是索引
goods.forEach(function(good, i) {
if (good.checked) {
totalPrice += good.price * good.number;
}
});
return totalPrice;
}
}
};
</script>
<style scoped>
.shop-container {
position: absolute;
top: 174px;
bottom: 0;
left: 0;
width: 100%;
overflow: hidden;
}
</style>