如有问题,欢迎各位大佬批评指正
图书购物车
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图书购物车</title>
</head>
<body>
<div id="app">
<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>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.date}}</td>
<td>
<button @click="increase(index)" :disabled="item.num >= 10">+</button>
{{item.num}}
<button @click="decrease(index)" :disabled="item.num <= 1">-</button>
</td>
<td>{{item.price | getPrice}}</td>
<td><button @click="removes(index)">移除</button></td>
</tr>
</tbody>
</table>
总价格:{{total | getPrice}}
</div>
<div v-else>
<h3>购物车为空</h3>
</div>
</div>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
books: [
{
id: 1,
name: '《三国演义》',
date: '2020.6.3',
num: 1,
price: 188
},
{
id: 2,
name: '《水浒传》',
date: '2020.6.3',
num: 1,
price: 188
},
{
id: 1,
name: '《西游记》',
date: '2020.6.3',
num: 1,
price: 188
}, {
id: 1,
name: '《红楼梦》',
date: '2020.6.3',
num: 1,
price: 188
}
],
},
methods: {
increase(index) {
this.books[index].num ++
},
decrease (index) {
this.books[index].num --
},
removes(index) {
this.books.splice(index,1);
},
//可以使用方法实现总价格计算,但是推荐使用计算属性来进行总价格的计算
// getTotalPrice() {
// let totalPrice = 0;
// for (i in this.books) {
// totalPrice += this.books[i].price * this.books[i].num;
// }
// return totalPrice;
// }
},
computed: {
total() {
let totalPrice = 0;
for(i in this.books) {
totalPrice += this.books[i].price * this.books[i].num;
}
return totalPrice;
}
},
//使用过滤器,返回指定格式数据
filters: {
getPrice(price) {
return "¥" + price.toFixed(2);
}
},
})
</script>
</body>
</html>