新建index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="app">
<table>
<thread>
<tr>
<th></th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thread>
<tbody>
<tr v-for="(item,index) in books">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.date}}</td>
<!--使用过滤器 过滤价格-->
<td>{{item.price | finalPrice}}</td>
<td>
<button @click="decr(index)">-</button>
{{item.count}}
<button @click="incr(index)">+</button>
</td>
<td>
<button @click="rem(index)">移除</button>
</td>
</tr>
</tbody>
</table>
<div>总价:{{totalPrice | finalPrice}}</div>
</div>
<script src="../../../js/vue.js"></script>
<script src="main.js"></script>
</body>
</html>
新建style.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;
}
新建main.js
const app = new Vue({
el: '#app',
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:'2008-10',
price:39.00,
count:1
},
{
id:4,
name:'<<代码大全>>',
date:'2006-3',
price:128.00,
count:1
},
]
},
methods: {
incr(index) {
this.books[index].count++;
},
decr(index) {
if (this.books[index].count === 0) {
return;
}
this.books[index].count--;
},
rem(index) {
this.books.splice(index, 1);
}
},
computed:{
totalPrice(){
let totalPrice = 0;
for (const item of this.books) {
totalPrice += item.price * item.count;
}
return totalPrice;
}
},
// 过滤器
filters:{
finalPrice(price){
// 拼接特殊符号,并保留两位小数
return '¥' + price.toFixed(2);
}
}
})
运行效果和上面一致
该案例是对上面的知识的综合运用,里面还提及了新的知识,filters过滤器
作者:彼岸舞
时间:2021\05\31
内容关于:VUE
本文属于作者原创,未经允许,禁止转发