本文實例為大家分享了vue.js實現簡單購物車的具體代碼,供大家參考,具體內容如下
這次我將給大家帶來一個vue.js實現購物車的小項目,如有不足請嚴厲指出。
購物車功能有:全選和選擇部分商品,選中商品總價計算,商品移除,以及調整購買數量等功能。
js主要有以下方法
加函數,減函數,手動修改數量判斷庫存函數,總價格計算函數,單選事件,全選事件,一共分為6個事件
具體效果如下圖
代碼在這裡
main.js
'use strict' var app = new Vue({ el: '#app', data: { list: [ { id: 1, name: 'iPhone 7', price: 6188, count: 1, check: true, }, { id: 2, name: 'iPad Pro', price: 5888, count: 1, check: false, }, { id: 3, name: 'MacBook Pro', price: 21488, count: 1, check: true, }, ] }, methods: { remove: function (index) { //移除商品 this.list.splice(index, 1); }, reduce: function (index) { //減少商品 this.list[index].count --; }, add: function (index) { //增加商品 this.list[index].count ++; }, selAll: function () { //商品全選 let isAll = document.querySelector('#all'); if (isAll.checked == true) { this.list.forEach(function(item, index) { item.check = true; }) } else { this.list.forEach(function(item, index) { item.check = false; }) } } }, computed: { totalPrices: function () { //計算總價 let totalPrices = 0; this.list.forEach(function (val, index) { if (val.check == true) totalPrices += parseFloat(val.price * val.count); }) return totalPrices.toString().replace(/B(?=(d{3})+$)/g, ','); //每三位數中間加一個‘,' } } })
index.html
全選商品名稱商品單價購買數量操作{{ item.name }}{{ item.price }}-{{ item.count }}+移除總價: ¥ {{ totalPrices }}購物車沒有商品
main.css
[v-cloak] { display: none; } #app { width: 500px; margin: 0 auto; } table { width: 100%; border: 1px solid #444; border-collapse: collapse; } th, td { padding: 8px 16px; border: 1px solid #444; text-align: left; } th { background: #89abd3; color: rgb(214, 224, 235); font-weight: 600; white-space: nowrap; }
[bom485332 ] vue.js實現簡單購物車功能已經有433次圍觀