<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
table {
border: 1px solid #e9e9e9;
border-collapse: collapse;
border-spacing: 0;
}
th,
td {
padding: 8px 16px;
border: 1px solid #e9e9e9;
text-align: center;
}
th {
background-color: #f7f7f7;
color: #5c6b77;
font-weight: 600;
}
</style>
</head>
<body>
<div id="jdg">
<div v-if="books.length!=0">
<table>
<thead>
<tr>
<th></th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(items,idx) in books">
<td>{{items.id}}</td>
<td>{{items.name}}</td>
<td>{{items.time}}</td>
<td>{{items.money|showPrice}}</td>
<!--过滤器语法-->
<td><button @click="subOne(idx)">-</button>{{items.nums}}<button @click="addOne(idx)">+</button>
</td>
<td><button @click="removeElement(idx)">移除</button></td>
</tr>
</tbody>
</table>
<h2>总价格:{{totolPrice|showPrice}}</h2>
</div>
<div v-else>
<h2>购物车为空</h2>
</div>
</div>
<script src="../vue.js"></script>
<script>
const app = new Vue({
el: '#jdg',
data: {
books: [
{
id: 1,
name: '《算法导论》',
time: '2006-9',
money: 89,
nums: 1
},
{
id: 2,
name: '《UNIX编程艺术》',
time: '2006-2',
money: 59,
nums: 1
},
{
id: 3,
name: '《编程珠玑》',
time: '2008-10',
money: 39,
nums: 1
},
{
id: 4,
name: '《代码大全》',
time: '2006-3',
money: 128,
nums: 1
}
]
},
computed: {
totolPrice() {
let ans = 0;
for (let i = 0; i < this.books.length; i++) {
ans += this.books[i].money * this.books[i].nums;
}
return ans;
}
},
methods: {
subOne(idx) {
let newM = this.books[idx];
if (newM.nums > 1) {
newM.nums--;
this.books.splice(idx, 1, newM);
} else {
let flag = confirm("确定把" + this.books[idx].name + "移出购物车吗?");
/*移除购物车*/
//alert(flag);
if (flag) {
this.books.splice(idx, 1);
}
}
},
addOne(idx) {
let newM = this.books[idx];
newM.nums++;
this.books.splice(idx, 1, newM);
},
removeElement(idx) {
this.books.splice(idx, 1);
}
},
filters: {//过滤器
showPrice(price) {
return '¥' + price.toFixed(2);
}
}
})
</script>
</body>
</html>
这个案例比较简单,需要注意一下过滤器的语法,filters中写的就是过滤器函数,应用语法是{{items.money|showPrice}},可以使得元素中内容以正确形式显示在页面上。