您好,登錄后才能下訂單哦!
本文小編為大家詳細(xì)介紹“Vue怎么實現(xiàn)購物車計算總價功能”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“Vue怎么實現(xiàn)購物車計算總價功能”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識吧。
效果:
代碼
html
<div id="app"> <div class="panel panel-info"> <div class="panel-heading"> <h4 class="panel-title">購物車</h4> </div> <div class="panel-body"> <div class="checkbox"> <label> <input type="checkbox" v-model="checkAll"> 全選 </label> </div> <ul class="list-group"> <li class="list-group-item" v-for="(item) in list" :key="item.id"> <div class="checkbox"> <label> <input type="checkbox" v-model="item.checked"> {{item.name}}--{{item.price}}*{{item.quantity}} <button type="button" @click="item.quantity>1?item.quantity-=1:1" class="btn btn-success">-</button> <button type="button" @click="item.quantity+=1" class="btn btn-success">+</button> </label> </div> </li> </ul> <p>總價:{{sumPrice}}</p> </div> </div> </div>
js
<script src="./libs/vue.js"></script> <script> new Vue({ el: "#app", data: { list: [ { id: 1, name: "小米10", price: 3999, checked: false, quantity: 1 }, { id: 2, name: "榮耀30", price: 2999, checked: false, quantity: 1 }, { id: 3, name: "魅族17", price: 3699, checked: false, quantity: 1 }, { id: 4, name: "蘋果11", price: 5499, checked: false, quantity: 1 } ], }, // computed計算屬性, // 他有一個特點,可以依賴當(dāng)前數(shù)據(jù)改變之后進(jìn)行重新計算 computed: { checkAll: { //設(shè)置值,當(dāng)點擊全選按鈕的時候觸發(fā) set(v) { this.list.forEach((item) => (item.checked = v)) }, //取值,當(dāng)列表中的值改變之后觸發(fā),需要return get() { return ( this.list.length === this.list.filter((item) => item.checked).length ) } }, //計算總價,選擇被選中的元素 sumPrice() { return this.list.filter((item) => item.checked).reduce((pre, cur) => { return pre + cur.price * cur.quantity }, 0) }, }, methods: { save() { console.log(this.list.filter((item) => item.checked)) } } }) </script>
結(jié)構(gòu)是用bootstrap寫的,記得下載并引入文件
<link rel="stylesheet" href="./bootstrap.min.css" rel="external nofollow" >
讀到這里,這篇“Vue怎么實現(xiàn)購物車計算總價功能”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領(lǐng)會,如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。