小项目总结
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<div id="app">
<div v-if="books.length">
<table>
<thead>
<tr>
<th>书id</th>
<th>书名</th>
<th>日期</th>
<th>书价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(book, index) in books">
<td>{{book.id}}</td>
<td>{{book.name}}</td>
<td>{{book.data}}</td>
<!--<td>{{'¥' + book.price.toFixed(2)}}</td>-->
<!--<td>{{getFinalPrice(book.price)}}</td>-->
<td>{{book.price | showPrice}}</td>
<td><button @click="decrement(index)" :disabled="book.count <= 0">-</button> {{book.count}} <button @click="increment(index)">+</button></td>
<td><button @click="removeClick(index)">移除</button></td>
</tr>
</tbody>
</table>
<div>总价格:{{totalPrice | showPrice}}</div>
<!--<button disabled>++++</button>-->
</div>
<h2 v-else>购物车为空</h2>
</div>
<script src="../js/vue.js"></script>
<script src="index.js"></script>
</body>
</html>
index.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;
text-align: center;
}
index.js
const book = new Vue({
el: '#app',
data: {
books: [
{
id: 1,
name: '《算法导论》',
data: '2006-9',
price: 120.00,
count:1
},
{
id: 2,
name: '《Linux编程艺术》',
data: '2006-10',
price: 85.00,
count:1
},
{
id: 3,
name: '《Python异步编程》',
data: '2006-11',
price: 59.00,
count:1
},
{
id: 4,
name: '《现在操作系统》',
data: '2006-12',
price: 39.00,
count: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
return this.books.reduce(function (preValue, book) {
return preValue + book.price * book.count
}, 0)
}
},
methods: {
getFinalPrice(price){
return '¥' + price.toFixed(2)
},
increment(index){
this.books[index].count++
},
decrement(index){
this.books[index].count--
},
removeClick(index) {
this.books.splice(index, 1)
}
},
filters: {
showPrice(price){
return '¥' + price.toFixed(2)
}
}
});
最终效果图

浙公网安备 33010602011771号