一、案例要求:
功能:點擊購買數量的加號、減號進行數量的增減;移除數據;合計總價格等,具體功能界面如下:
二、案例結構:
Index.html 界面
main.js 功能處理代碼
style.css 樣式
三、代碼實現(功能比較簡單,就直接上代碼了)
Index.html 界面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="app">
<div v-if="books.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 books">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.date}}</td>
<td>{{item.price | showPrice}}</td>
<td>
<button @click="decrement(index)" v-bind:disabled="item.count <= 1">-</button>
{{item.count}}
<button @click="increment(index)">+</button>
</td>
<td><button @click="removeClick(index)">移除</button></td>
</tr>
</tbody>
</table>
<h2>總價格:{{totalPrice | showPrice}}</h2>
</div>
<h2 v-else>購物車爲空</h2>
</div>
<script src="../js/vue.js"></script>
<script src="main.js"></script>
</body>
</html>
main.js 功能處理代碼
const app = new Vue({
el: '#app',
data: {
books: [
{
id: 1,
name: '《算法大師》',
date: '2020-09',
price: 89.9,
count: 1
},{
id: 2,
name: '《思維簡史》',
date: '2010-09',
price: 100.00,
count: 1
},{
id: 3,
name: '《彙編語言》',
date: '2030-10',
price: 69.9,
count: 1
},{
id: 4,
name: '《計算機等級考試》',
date: '2020-01',
price: 56.88,
count: 1
},{
id: 5,
name: '《營養師》',
date: '2015-08',
price: 34,
count: 1
},
],
btnEnable: true
},
methods: {
getFinalPrice(price) {
return '¥' + price.toFixed(2)
},
increment(index) {
console.log('increment',index);
this.books[index].count += 1
},
decrement(index) {
console.log('decrement',index);
this.books[index].count -= 1
},
removeClick(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
// 高階函數 reduce()
return this.books.reduce((function (prevValue, book) {
return prevValue + book.price * book.count
} ),0)
}
},
filters: {
showPrice(price) {
return '¥' + price.toFixed(2)
}
},
})
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;
}
小技巧:
1、reduce函數,可以理解爲“合計”的一個動作
2、filters,過濾器:進一步對數據進行處理