实现购物车的数量的增加减少,以及价格对应的变化,实现删除操作
<div id="app">
<cop :books="books" />
</div>
<template id="cnp">
<div>
<div v-if="books.length">
<table>
<thead>
<tr>
<th></th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in books">
<td>{{Number(item.id)+1}}</td>
<td>{{item.date}}</td>
<td>{{item.name}}</td>
<!-- <td>{{getprice(item.price)}}</td> -->
<td>{{item.price|showprice}}</td>
<td>
<button @click="decrement(index)" :disabled="item.count==1">-</button>
{{item.count}}
<button @click="increment(index)">+</button>
</td>
<td @click="removeClick(index)">删除</td>
</tr>
</tbody>
</table>
<h2>总价格:{{totalPrice|showprice}}</h2> </div>
<h2 v-else>购物车为空</h2>
</div>
</template>
<script>
// 注册全局组件
Vue.component("cop", {
template: "#cnp",
props: {
books: Array
},
methods: {
// getprice(price) {
// return '¥' + Number(price).toFixed(2)
// // return '¥' + price.toFixed(2)
// }
decrement(index) {
this.books[index].count--;
},
increment(index) {
this.books[index].count++;
},
removeClick(index) {
this.books.splice(index, 1);
}
},
filters: {
showprice(price) {
return '¥' + Number(price).toFixed(2)
}
},
computed: {
totalPrice() {
// 使用v-of遍历数组,计算总价格
// let totalPrice = ""
// for (let item of this.books) {
// totalPrice = Number(totalPrice) + item.price * item.count;
// }
// return totalPrice
// 使用reduce来计算总价格
return this.books.reduce((preValue, item) => {
return Number(preValue) + item.price * item.count
}, 0)
}
}
})
const app = new Vue({
el: "#app",
data: {
books: [
{
id: "0",
name: "c语言从入门到放弃",
date: '2021-2-12',
price: "88.9",
count: 1
},
{
id: "1",
name: "java高级编程",
date: '2021-2-10',
price: "20.00",
count: 1
},
{
id: "2",
name: "操作系统",
date: '2021-2-9',
price: "50.00",
count: 1
},
{
id: "3",
name: "数据结构",
date: '2021-2-1',
price: "40",
count: 1
},
]
},
})
</script>