Vue 購物車案例練習
1.購物車案例
經(jīng)過一系列的學習,我們這里來練習一個購物車的案例
需求:使用
vue寫一個表單頁面,頁面上有購買的數(shù)量,點擊按鈕+或者-,可以增加或減少購物車的數(shù)量,數(shù)量最少不得少于0,點擊移除按鈕,會移除該商品,當把所有的商品移除后,頁面上的表單消失,然后出現(xiàn)文字:購物車為空,表單下方是商品的總價格,隨著商品的數(shù)量增加而增加,默認是0元,
總體效果如下:

2.代碼實現(xiàn)
<!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>購買數(shù)量</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位小數(shù)的
filters: {
showPrice(price){
return '¥' + price.toFixed(2)
}
}
})
</script>
</body>
</html>
3.總結
v-for:循環(huán),循環(huán)books列表
v-on:事件監(jiān)聽,監(jiān)聽點擊事件
disabled:按鈕是否可以點擊的屬性,為True可點擊,為False不可點擊,增加判斷條件:disabled="book.count <= 0"當購物車數(shù)量≤0,則無法點擊
v-if和v-else:條件判斷,判斷books的列表長度,如果有長度展示列表,如果長度為0則展示文字購物車為空
filters:自定義過濾器,過濾價格,使本身的價格過濾后帶有2位小數(shù)
computed:計算屬性,計算購物的總價格
到此這篇關于Vue 購物車案例練習的文章就介紹到這了,更多相關Vue 購物車練習內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
解決ant-design-vue中menu菜單無法默認展開的問題
這篇文章主要介紹了解決ant-design-vue中menu菜單無法默認展開的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10
vxe-list?vue?如何實現(xiàn)下拉框的虛擬列表
這篇文章主要介紹了vxe-list?vue?如何實現(xiàn)下拉框的虛擬列表,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06
Vue實現(xiàn)監(jiān)聽dom節(jié)點寬高變化方式
這篇文章主要介紹了Vue實現(xiàn)監(jiān)聽dom節(jié)點寬高變化方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10

