【前端案例】 24 - Vue实现简单的购物车案例 :计算属性
2021-01-15 本文已影响0人
itlu
(一) vue 实现简单的购物车案例
vue购物车案例- 实现购物车案例简单的修改数量,移除商品,计算数量,计算总价格的功能。
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no"
,maximum-scale=1.0,minimum-scale=1.0>
<title>书籍购物车</title>
<link rel="stylesheet" href="./index.css">
</head>
<body>
<div id="app">
<div class="books-body" 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="(item,index) in books">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.date}}</td>
<!-- 使用过滤器 -->
<td>{{item.price|showPrice}}</td>
<!-- <td>{{item.price.toFixed(2)}}</td>-->
<!--<td>{{item.price}}</td>-->
<td>
<button @click="increment(index)">+</button>
{{item.count}}
<button :disabled="item.count <= 1" @click="decrement(index)">-</button>
</td>
<td>
<button @click="btnRemoveClick(index)">移除</button>
</td>
</tr>
</tbody>
</table>
<h2>总价格{{totalPrice}}</h2>
</div>
<div class="clear-car" v-else>
<h2>购物车为空</h2>
</div>
</div>
<script src="../../js/vue.js"></script>
<script src="./index.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;
}
js
const app = new Vue({
el: '#app',
data: {
books: [
{
id: 1,
name: '《Effective Java中文版》',
date: '2018-12-11',
price: 100.00,
count: 1
},
{
id: 2,
name: '《Spring in Action: 5 edition》',
date: '2018-01',
price: 199.00,
count: 1
},
{
id: 3,
name: '《Spring揭秘》',
date: '2009-01',
price: 89.00,
count: 1
},
{
id: 4,
name: '《Spring实战(第3版》',
date: '2013-01',
price: 128.00,
count: 1
},
]
},
methods: {
/**
* 递增
* @param index
*/
increment(index) {
this.books[index].count++;
},
/**
* 递减
* @param index
*/
decrement(index) {
this.books[index].count--;
},
/**
* 移除购物车中的图书
* @param index
*/
btnRemoveClick(index) {
console.log('点我');
this.books.splice(index, 1);
}
},
filters: {
showPrice(price) {
return '¥' + price.toFixed(2);
}
},
computed: {
/**
* 总价格
*/
totalPrice() {
let totalPrice = 0;
for (let item of this.books) {
totalPrice += item.count * item.price;
}
return totalPrice;
}
}
});
(二)vue中的过滤器
-
vue
中的过滤器,类似计算属性的使用,需要传递参数,返回被修饰或者过滤之后的值。{{params | filter}}
<div id="app">
<h2>{{message | messageFiltered}}</h2>
</div>
<script src="../../js/vue.js"></script>
const app = new Vue({
el: '#app',
data: {
message: '我们不一样!'
},
filters: {
messageFiltered(message) {
return '【' + message + '】';
}
}
});