<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
table {
border: 1px solid #e9e9e9;
border-spacing: 0;
border-collapse: collapse;
}
th,
td {
padding: 8px 16px;
border: 1px solid #e9e9e9;
text-align: center;
}
th {
background-color: #f7f7f7;
color: #5c6d77;
}
</style>
</head>
<body>
<div id="app">
<div v-if="books.length">
<table>
<thead>
<!-- 循环表头 -->
<th v-for="item in shopTitle">{{item}}</th>
</thead>
<tbody>
<!-- 循环每一项 -->
<tr v-for="(item,index) in books">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.date}}</td>
<td>{{item.price | showPrice}}</td>
<td>
<!-- 减的时候,当数量<=1时不能点击 传入index是为了确定当前点击的减的项是哪一个-->
<button @click="discrement(index)" :disabled="item.count<=1">-</button>
{{item.count}}
<button @click="increment(index)">+</button>
</td>
<td>
<button @click="removeHandle(index)">移除</button>
</td>
</tr>
</tbody>
</table>
<!-- 这里使用计算属性=====是因为他是动态变化的值 -->
<h2>总价:{{totalPrice}}</h2>
</div>
<div v-else>
<h2>购物车当前为空,快去添加心仪的产品吧</h2>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
// 模拟数据
shopTitle: ['', '书籍名称', '出版日期', '价格', '购买数量', '操作'],
books: [{
id: 1,
name: '《JavaScript高级程序设计(第三版)》',
date: "2012-6",
price: 99.00,
count: 1
},
{
id: 2,
name: '《JavaScript高级程序设计(第三版)》',
date: "2012-6",
price: 99.00,
count: 1
},
{
id: 3,
name: '《JavaScript高级程序设计(第三版)》',
date: "2012-6",
price: 99.00,
count: 1
},
{
id: 4,
name: '《JavaScript高级程序设计(第三版)》',
date: "2012-6",
price: 99.00,
count: 1
}]
},
methods: {
// 数量每次减一
discrement(index) {
this.books[index].count--;
},
// 数量每次加一
increment(index) {
this.books[index].count++;
},
// 删除当前点击的数组的一个
removeHandle(index) {
this.books.splice(index, 1)
}
},
// 价格求和
filters: {
showPrice(price) {
return '¥' + price.toFixed(2)//保留数值为小数点后两位的值,赋值为新的值,前面是字符串拼接
}
},
// 计算属性---使用时不需要加小括号
computed: {
totalPrice() {
let totalPrice = 0
// for in 方法
// for (let i in this.books) {
// totalPrice += this.books[i].price * this.books[i].count;
// console.log(i);
// }
// for of 方法
for (let i of this.books) {
console.log(i); //可以看一下i打印的是什么
totalPrice += i.price * i.count
}
return totalPrice
}
}
})
</script>
</body>
</html>