Vue商品添加到购物车
生活随笔
收集整理的這篇文章主要介紹了
Vue商品添加到购物车
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
用Vue實現把商品添加到購物車然后計算購物車里商品總金額。
功能分析:
1.商品添加到購物車
2.購物車顯示商品的名稱數量價格
3.計算購物車商品的總金額
4.刪除購物車商品
效果演示
原始樣式
添加商品
增加商品數量
下面向大家展示一下實現的過程。
代碼演示
注意:
引入Vue.js架包
總體代碼
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title></title><script src="js/vue.js"></script></head> <style>tr,th{width: 110px;height: 30px;text-align: center;} </style> <body><div id="shop"></div></body> <script >//購物車模塊var Chat={//子組件接收父組件傳遞的數據props:['chatarr'],template:`<div>我的課程<table border="1"><tr><th>選中</th><th>課程</th><th>數量</th><th>價格</th></tr><tr v-for='(chat,index) in chatarr'><td><input type="checkbox" v-model='chat.active' name=""></td><td>{{chat.text}}</td><td><span @click='reducecount(index)'>-</span>{{chat.count}}<span @click='addcount(index)'>+</span></td><td>{{chat.count*chat.price}}</td></tr><tr><td colspan='2'>選中的課程:{{activeCount}}/{{count}}</td><td colspan='2'>需付金額:{{totalpirce}}</td></tr></table></div>`,computed:{activeCount(){return this.chatarr.filter(v=>v.active).length},count(){return this.chatarr.length},totalpirce(){let total = 0;this.chatarr.forEach(v=>{if(v.active){total+=v.price*v.count}})return total}},methods:{//點擊減號減少商品數量reducecount(index){if(this.chatarr[index].count>1){this.chatarr[index].count--}else{if(window.confirm(`確認刪除${this.chatarr[index].text}?`))this.chatarr.splice(index,1)}},//點擊加號增加商品數量addcount(index){this.chatarr[index].count++}, },watch:{chatarr:{handler(){window.localStorage.setItem('chat',JSON.stringify(this.chatarr))},deep:true}}}//實例化new Vue({el:'#shop',template:`<div><div>課程:<input type="text" name="" v-model='course'>價格:<input type="text" name="" v-model='price'><button @click='addcourse'>添加課程</button></div><ul><li v-for='(list,index) in classlist'>課程名稱:{{list.text}}---價格:{{list.price}}<button @click='addtochat(index)'>添加到我的課程</button></li></ul><!-- 父組件給子組件傳遞數據 --><chat :chatarr='chatarr' ></chat></div>`,components:{Chat},data:{classlist:[],course:'',price:'',//存放購物車信息的數組chatarr:[],},methods:{//添加商品addcourse(){//插入數據this.classlist.push({text:this.course,price:this.price})//清空輸入的內容this.course=''this.price=''},//添加到購物車addtochat(index){const goods=this.classlist[index]const result = this.chatarr.find(v=>v.text==goods.text)if(result){result.count+=1}else{this.chatarr.push({...goods,count:1,active:true})}},},created(){if(window.localStorage.getItem('chat')!=null){//獲取本地存儲數據this.chatarr=JSON.parse(window.localStorage.getItem('chat')) }}})</script> </html>掃一掃關注我的公眾號獲取更多資訊!!!
總結
以上是生活随笔為你收集整理的Vue商品添加到购物车的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python模块使用相对路径还是绝对路径
- 下一篇: Vue 购物车案例