vue購物車小案例
阿新 • • 發佈:2021-02-14
技術標籤:vue
實現購物車的數量的增加減少,以及價格對應的變化,實現刪除操作
<div id="app">
<cop :books="books" />
</div>
<template id="cnp">
<div>
<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>{{Number(item.id)+1}}</td>
< td>{{item.date}}</td>
<td>{{item.name}}</td>
<!-- <td>{{getprice(item.price)}}</td> -->
<td>{{item.price|showprice}}</td>
<td>
<button @click="decrement(index)" :disabled="item.count==1">-</button>
{{item.count}}
<button @click="increment(index)">+</button>
</td>
<td @click="removeClick(index)">刪除</td>
</tr>
</tbody>
</table>
<h2>總價格:{{totalPrice|showprice}}</h2> </div>
<h2 v-else>購物車為空</h2>
</div>
</template>
<script>
// 註冊全域性元件
Vue.component("cop", {
template: "#cnp",
props: {
books: Array
},
methods: {
// getprice(price) {
// return '¥' + Number(price).toFixed(2)
// // return '¥' + price.toFixed(2)
// }
decrement(index) {
this.books[index].count--;
},
increment(index) {
this.books[index].count++;
},
removeClick(index) {
this.books.splice(index, 1);
}
},
filters: {
showprice(price) {
return '¥' + Number(price).toFixed(2)
}
},
computed: {
totalPrice() {
// 使用v-of遍歷陣列,計算總價格
// let totalPrice = ""
// for (let item of this.books) {
// totalPrice = Number(totalPrice) + item.price * item.count;
// }
// return totalPrice
// 使用reduce來計算總價格
return this.books.reduce((preValue, item) => {
return Number(preValue) + item.price * item.count
}, 0)
}
}
})
const app = new Vue({
el: "#app",
data: {
books: [
{
id: "0",
name: "c語言從入門到放棄",
date: '2021-2-12',
price: "88.9",
count: 1
},
{
id: "1",
name: "java高階程式設計",
date: '2021-2-10',
price: "20.00",
count: 1
},
{
id: "2",
name: "作業系統",
date: '2021-2-9',
price: "50.00",
count: 1
},
{
id: "3",
name: "資料結構",
date: '2021-2-1',
price: "40",
count: 1
},
]
},
})
</script>