購物車案例

經過一系列的學習,我們這裡來練習一個購物車的案例

  需求:使用vue寫一個表單頁面,頁面上有購買的數量,點選按鈕+或者-,可以增加或減少購物車的數量,數量最少不得少於0,點選移除按鈕,會移除該商品,當把所有的商品移除後,頁面上的表單消失,然後出現文字:購物車為空,表單下方是商品的總價格,隨著商品的數量增加而增加,預設是0元,總體效果如下:

程式碼實現

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="../js/vue.js"></script>
<style>
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;
}
</style>
</head>
<body>
<div id="app">
<div v-if="books.length">
<table>
<thread>
<tr>
<th></th>
<th>書籍名稱</th>
<th>出版日期</th>
<th>價格</th>
<th>購買數量</th>
<th>操作</th>
</tr>
</thread>
<tbody>
<tr v-for="(book, index) in books" :key="book">
<td>{{index+1}}</td>
<td>{{book.name}}</td>
<td>{{book.publish_date}}</td>
<td>{{book.price | showPrice}}</td>
<td>
<button @click="decrease(index)" :disabled="book.count <= 0">-</button>
{{book.count}}
<button @click="increase(index)">+</button>
</td>
<td>
<button @click="removeClick(index)">移除</button>
</td>
</tr>
</tbody>
</table>
<p>總價:{{totalPrice | showPrice}}</p>
</div>
<h2 v-else>購物車為空</h2>
</div>
<script>
const app = new Vue({
el: "#app",
data: {
books: [
{"name":"演算法導論", "publish_date":"2006-9", "price":20.00, "count": 0},
{"name":"UNIX程式設計藝術", "publish_date":"2006-2", "price":30.00, "count": 0},
{"name":"程式設計技術", "publish_date":"2008-10", "price":40.00, "count": 0},
{"name":"程式碼大全", "publish_date":"2006-3", "price":50.00, "count": 0},
],
},
methods: {
// 增加+
decrease(index){
this.books[index].count-=1
},
// 減少-
increase(index){
this.books[index].count+=1
},
// 移除按鈕
removeClick(index){
this.books.splice(index, 1)
}
},
computed: {
// 計算總價格
totalPrice(){
let totalPrice = 0
for (let item of this.books){
totalPrice += item.price * item.count
}
return totalPrice
}
},
// 過濾器,將價格過濾成有2位小數的
filters: {
showPrice(price){
return '¥' + price.toFixed(2)
}
}
})
</script>
</body>
</html>

以上就是全部程式碼,當中使用到了很多知識點

  • v-for:迴圈,迴圈books列表
  • v-on:事件監聽,監聽點選事件
  • disabled:按鈕是否可以點選的屬性,為True可點選,為False不可點選,增加判斷條件:disabled="book.count <= 0"當購物車數量≤0,則無法點選
  • v-ifv-else:條件判斷,判斷books的列表長度,如果有長度展示列表,如果長度為0則展示文字購物車為空
  • filters:自定義過濾器,過濾價格,使本身的價格過濾後帶有2位小數
  • computed:計算屬性,計算購物的總價格