一、界面搭建
html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div id="box">
<table>
<thead>
<tr>
<th></th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="item in books">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.date}}</td>
<td>{{item.price}}</td>
<td>
<button @click="btnAdd({{item.count}})">+</button>
{{item.count}}
<button @click="btnSub">-</button>
</td>
<td>
<button>移除</button>
</td>
</tr>
</tbody>
</table>
</div>
<script src="../js/vue.js"></script>
<script src="./main.js"></script>
</body>
</html>
CSS文件
table {
border: 1px solid #e9e9e9;
border-collapse: collapse;
border-spacing: 0;
}
th, td {
padding: 8px 16px;
border: 1px solid #e9e9e9;
text-align: left;
}
th {
background-color: #f7f7f7;
color: #5c6b77;
font-weight: 600;
}
二、过滤器
在Vue中使用filters定义
const box = new Vue({
el: "#box",
filters: {
showPrice(price) {
return '¥' + price.toFixed(2)
}
}
})
在html中在属性后面添加 | 过滤器
调用
<td>{{item.price | showPrice}}</td>
三、案例完成
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div id="box">
<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>{{item.price | showPrice}}</td>
<td>
<!-- 数量增加功能 -->
<button @click="addBtn(index)">+</button>
{{item.count}}
<!-- 数量减少功能 -->
<!-- 如果数量小于等于1, 就让按钮禁用 -->
<button @click="subBtn(index)"
:disabled="item.count <= 1">-</button>
</td>
<td>
<!-- 移除功能 -->
<button @click="removeBtn(index)">移除</button>
</td>
</tr>
</tbody>
</table>
<!-- 按照规定格式显示总价格 -->
<h2>总价格: {{totalPrice | showPrice}}</h2>
</div>
<script src="../js/vue.js"></script>
<script src="./main.js"></script>
</body>
</html>
const box = new Vue({
el: "#box",
data: {
books: [{
id: 1,
name: "<<算法导论>>",
date: "2006-9",
price: 85.00,
count: 1
},{
id: 2,
name: "<<UNIX编程艺术>>",
date: "2006-2",
price: 59.00,
count: 1
},{
id: 3,
name: "<<编程珠玑>>",
date: "2006-6",
price: 39.00,
count: 1
},{
id: 4,
name: "<<代码大全>>",
date: "2006-3",
price: 158.00,
count: 1
}]
},
methods: {
// 增加数量
addBtn(index) {
this.books[index].count++;
},
// 减少数量
subBtn(index) {
this.books[index].count--;
},
// 移除
removeBtn(index) {
this.books.splice(index, 1);
}
},
computed: {
// 总价格
totalPrice() {
let totalP = 0;
for(let book of this.books) {
totalP += book.count * book.price;
}
return totalP;
}
},
filters: {
// 按照规定的格式显示
showPrice(price) {
return "¥" + price.toFixed(2);
}
}
})