我们想做如下效果
想完成的功能如下
1.价格生成人民币格式
2.购买数量可从1开始加数量
3.可以移除当前行
4.计算总价格
5.当购物车清空时换另外一种效果
<!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>
* {
margin: 0;
padding: 0;
}
table {
width: 500px;
height: 50px;
margin: 10px;
border-collapse: collapse;
}
thead {
background-color: rgb(224, 223, 223);
}
td {
border: 1px solid rgb(196, 194, 194);
padding: 5px;
text-align: center;
}
button {
width: 17px;
height: 17px;
}
.yichu {
width: 40px;
height: 20px;
}
h2 {
padding: 10px;
color: rgb(165, 162, 162);
}
</style>
</head>
<body>
<div id='app'>
<div v-if="books.length">
<table>
<thead>
<tr>
<td>序号</td>
<td>书籍名称</td>
<td>出版日期</td>
<td>价格</td>
<td>购买数量</td>
<td>操作</td>
</tr>
</thead>
<tbody>
<tr v-for='(items, index) in books'>
<!-- <td v-for='value in items'>{{value}}</td> -->
<td>{{items.id}}</td>
<td>{{items.name}}</td>
<td>{{items.date}}</td>
<!-- <td>{{'¥'+Number(items.price).toFixed(2)}}</td> -->
<!-- <td>{{getFinalPrice(items.price)}}</td> -->
<td>{{items.price|showPrice}}</td>
<td>
<button @click='sub(index)' v-bind:disabled="items.count <= 1 ">-</button>
{{items.count}}
<button @click='add(index)'>+</button>
</td>
<td><button class="yichu" @click="removeHandle">移除</button></td>
</tr>
</tbody>
</table>
<h3> 总价:{{totalPrice}}</h3>
</div>
<h2 v-else>购物车为空~~快去加购宝贝吧~~</h2>
</div>
<script src='../js/vue.js'></script>
<script>
const app = new Vue({
el: '#app',
data: {
isShow: true,
books: [
{
id: 1,
name: '《算法》',
date: '2008-1',
price: '95',
count: 1,
},
{
id: 2,
name: '《代码大全》',
date: '2008-1',
price: '45',
count: 1,
},
{
id: 3,
name: '《编程与艺术》',
date: '2008-1',
price: '65',
count: 1,
}
]
},
methods: {
// getFinalPrice(price) {
// return '¥' + Number(price).toFixed(2)
// },
sub(index) {
this.books[index].count--;
// console.log('sub', index);
},
add(index) {
this.books[index].count++;
},
removeHandle(index) {
this.books.splice(index, 1)
}
},
computed: {
totalPrice() {
let totalPrice = 0;
for (let i = 0; i < this.books.length; i++) {
totalPrice += this.books[i].price * this.books[i].count;
}
return totalPrice
}
},
filters: {
showPrice(price) {
return '¥' + Number(price).toFixed(2)
}
}
})
</script>
</body>
</body>