<vue 基础知识 8、购物车样例>
代码结构

一、 效果
1、 展示列表v-for
2、 购买数量增加减少,使用@click触发回调函数。
减少的时候如果已经为1了就不让继续减少,使用了v-bind绑定属性
3、 移除也是使用@click触发回调函数。
4、 总价和价格里前面增加一个¥使用了过滤器
5、 总价的计算使用了计算属性

二、代码
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="app">
<div v-if="list.length">
<table>
<thead>
<tr>
<th></th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in list" >
<td>{{index+1}}</td>
<td>{{item.name}}</td>
<td>{{item.date}}</td>
<td>{{item.price | showPrice}}</td>
<td>
<button @click="decrement(index)" :disabled="item.count===1">-</button>
{{item.count}}
<button @click="increment(index)">+</button>
</td>
<td>
<button @click="handleRemove(index)">移除</button>
</td>
</tr>
</tbody>
</table>
<div>总价: {{totalPrice | showPrice}}</div>
</div>
<div v-else>购物车为空</div>
</div>
<script src="vue.js"></script>
<script src="index.js"></script>
</body>
</html>
index.js
let app = new Vue({
el: '#app',
data: {
list: [
{
id: 1,
name: '《三国演义》',
date: '1985-9',
price: 100.00,
count: 1
},
{
id: 2,
name: '《红楼梦》',
date: '1965-2',
price: 20.00,
count: 1
},
{
id: 3,
name: '《西游记》',
date: '1983-10',
price: 30.00,
count: 1
},
{
id: 4,
name: '《水浒传》',
date: '1981-3',
price: 145.00,
count: 1
},
]
},
methods: {
decrement(index) {
this.list[index].count--;
},
increment(index) {
this.list[index].count++;
},
handleRemove(index) {
this.list.splice(index, 1);
}
},
filters: {
showPrice(value) {
return '¥' + value.toFixed(2)
}
},
computed: {
totalPrice() {
let total = 0;
//方法一
for (let i = 0; i < this.list.length; i++) {
let item = this.list[i];
total += item.price * item.count;
}
return total
}
}
})
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;
}
浙公网安备 33010602011771号