Vue.js實(shí)現(xiàn)開發(fā)購物車功能的方法詳解
本文實(shí)例講述了Vue.js實(shí)現(xiàn)開發(fā)購物車功能的方法。分享給大家供大家參考,具體如下:
購物車一般包含商品名稱、單價(jià)、數(shù)量等信息,數(shù)量可以任意新增或減少,商品項(xiàng)也可刪除,還可以支持全選或多選:

我們把這個(gè)小項(xiàng)目分為三個(gè)文件:
- index.html (頁面)
- index.js (Vue 腳本)
- style.css (樣式)
1 index.js
首先在 js 中初始化 Vue 實(shí)例,整體模板如下:
var app = new Vue({
el: '#app',
data: {
...
},
mounted: function () {
...
},
computed: {
...
},
methods: {
...
}
});
一般來說,這里的 data 來源于服務(wù)端數(shù)據(jù),這里為了簡便,所以直接定義好的數(shù)據(jù):
data: {
/**
* 購物車中的商品列表
*/
list: [
{
id: 1,
name: '韓國進(jìn)口海牌海苔',
price: 39.9,
count: 1
},
{
id: 2,
name: '印尼進(jìn)口 Nabati 麗巧克(Richoco)休閑零食 巧克力味 威化餅干',
price: 11.8,
count: 1
},
{
id: 3,
name: '菲律賓進(jìn)口 道吉草 奶油夾',
price: 6.5,
count: 1
}
],
//選中的商品列表,用于計(jì)算總價(jià)
checkList: []
}
list 用于展示 購物車中的商品列表。
checkList 用于表示勾選中的商品列表,后面,我們會(huì)利用它來計(jì)算選中商品的總價(jià)。
mounted: function () {
//默認(rèn)全選
this.checkAll();
this.checkAllElement(document.querySelector(".checkAll"));
}
當(dāng) mounted 時(shí),默認(rèn)全選購物車內(nèi)的所有商品。
computed: {
/**
* 總價(jià)
* @returns {string}
*/
totalPrice: function () {
var total = 0;
for (var i = 0; i < this.checkList.length; i++) {
var item = this.checkList[i];
total += item.price * item.count;
}
return total.toLocaleString();
}
}
在計(jì)算屬性中,我們定義了總價(jià)的計(jì)算方式,它會(huì)綁定勾選的 checkList 來計(jì)算總價(jià)。之所以使用 toLocaleString 方法,是因?yàn)樾?shù)部分會(huì)自動(dòng)四舍五入,而且還會(huì)以千分位表示出來,很方便哦O(∩_∩)O~
methods: {
/**
* 減少購買數(shù)量
* @param index
*/
reduceCount: function (index) {
if (this.list[index].count === 1) return;
this.list[index].count--;
},
/**
* 增加購買數(shù)量
* @param index
*/
addCount: function (index) {
this.list[index].count++;
},
/**
* 移除商品
* @param index
*/
remove: function (index) {
console.log("remove-index:" + index);
this.list.splice(index, 1);
//獲取商品序號(hào)
var id = index + 1;
//移除實(shí)際參與計(jì)算的商品
var $checkList = this.checkList;
for (var i = 0; i < $checkList.length; i++) {
var item = $checkList[i];
if (item.id == id) {
$checkList.splice(i, 1);
}
}
},
/**
* 全選或全不選
* @param event
*/
checkAllOrNot: function (event) {
if (event.target.checked) {//全選
this.checkAll();
console.log("checkList:" + this.checkList);
} else { // 全不選
console.log("全不選");
this.checkInItems('noCheckAll');
this.checkList.splice(0);//清空數(shù)組
}
},
/**
* 全選
*/
checkAll: function () {
console.log("全選");
this.checkInItems('checkAll');
this.checkList = this.list.concat();//復(fù)制商品列表
},
/**
* 全選或全不選
* @param type checkAll:全選;其他:全不選
*/
checkInItems: function (type) {
var items = document.querySelectorAll('.checkItem');
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (type === 'checkAll') {
item.checked = true;
} else {
item.checked = false;
}
}
},
/**
* 勾選或不勾選
*/
checkItem: function (event, index) {
console.log("checkItem");
var element = event.target;
var $allCheck = document.querySelector(".checkAll");
if (element.checked) {//勾選,加入已選擇列表
this.checkList.push(this.list[index]);
this.checkAllElement($allCheck);
} else {//不勾選,從已選擇列表中去除
this.checkList.splice(index, 1);
$allCheck.checked = false;
}
},
/**
* 勾選全選框
* @param element
*/
checkAllElement: function (element) {
//如果所有的商品都已被勾選,則勾選全選框
if (this.checkList.length == this.list.length) {
element.checked = true;
}
}
}
在 methods 中,我們定義了以下功能方法:
減少與增加購買數(shù)量。在減少購買數(shù)量方法中,我們對當(dāng)前所對應(yīng)商品的數(shù)量進(jìn)行了二次確認(rèn),讓代碼變得更加健壯(HTML 模板可能被修改,button 被替換為 div 或者 span,那么 disabled 樣式就變得無效啦)。
移除某件商品。因?yàn)橘徫镘囍械纳唐妨斜砼c實(shí)際勾選的商品列表數(shù)量上有可能存在差異,所以我們必須通過找到商品 ID 再進(jìn)行刪除。
勾選相關(guān)操作(全選、全不選、單選、單不選等)
2 style.css
[v-cloak] {
display: none;
}
table {
border: 1px solid #e9e9e9;
border-collapse: collapse;
border-spacing: 0;
empty-cells: show;
}
th {
font: bold 12px "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
color: #4f6b72;
border-right: 1px solid #C1DAD7;
border-bottom: 1px solid #C1DAD7;
border-top: 1px solid #C1DAD7;
letter-spacing: 2px;
text-transform: uppercase;
text-align: left;
padding: 6px 6px 6px 12px;
background: #CAE8EA;
}
td {
border-right: 1px solid #C1DAD7;
border-bottom: 1px solid #C1DAD7;
background: #fff;
font-size:14px;
padding: 6px 6px 6px 12px;
color: #4f6b72;
}
這里定義了 v-cloak 樣式,用于解決網(wǎng)絡(luò)慢時(shí)的閃屏問題。還定義了表格的相關(guān)樣式。
3 index.html
接著在 index.html 中引入 Vue 腳本與樣式文件。基本模板如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>購物車</title> <link rel="stylesheet" type="text/css" href="style.css" rel="external nofollow" > </head> <body> <div id="app" v-cloak> ... </div> <script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script> <script src="index.js"></script> </body> </html>
因?yàn)橛锌赡苜徫镘囍械纳唐繁蝗縿h除,所以我們在此加了判斷,如果列表為空,則給出友好提示:
<template v-if="list.length"> ... </template> <!--當(dāng)購物車為空時(shí),則提示--> <div v-else>購物車內(nèi)暫時(shí)沒有商品</div>
接著用 table 來展示購物車內(nèi)的商品列表:
<table>
<thead>
<tr>
<th><input id="checkAll" type="checkbox" class="checkAll" @click="checkAllOrNot($event)"></th>
<th>序號(hào)</th>
<th>商品</th>
<th>單價(jià)</th>
<th>數(shù)量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in list">
<td><input type="checkbox" class="checkItem" @click="checkItem($event,index)"></td>
<td>{{index+1}}</td>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td>
<button @click="reduceCount(index)" :disabled="item.count===1">-</button>
{{item.count}}
<button @click="addCount(index)">+</button>
</td>
<td>
<button @click="remove(index)">刪除</button>
</td>
</tr>
</tbody>
</table>
<div>總價(jià):¥{{totalPrice}}</div>
使用 v-for 指令,循環(huán)迭代出商品列表。
表格內(nèi)的每一個(gè)勾選框與按鈕都綁定了相應(yīng)的事件。全選框與每一行的勾選框還傳入了原生 DOM 事件 $event,用于獲取當(dāng)前所操作的元素。
*這里對減少商品數(shù)量的按鈕進(jìn)行了判斷,當(dāng)相應(yīng)商品的數(shù)量只剩下一個(gè)時(shí),綁定 disabled 樣式,讓它變成不可用。
4 演示

本文jsfiddle示例DEMO地址:https://jsfiddle.net/deniro/hvq1y72o/
希望本文所述對大家vue.js程序設(shè)計(jì)有所幫助。
相關(guān)文章
vue中g(shù)et方法\post方法如何傳遞數(shù)組參數(shù)詳解
在前后端交互的時(shí)候,有時(shí)候需要通過get或者delete傳遞一個(gè)數(shù)組給后臺(tái),下面下面這篇文章主要給大家介紹了關(guān)于vue中g(shù)et方法\post方法如何傳遞數(shù)組參數(shù),文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-03-03
vue 獲取url參數(shù)、get參數(shù)返回?cái)?shù)組的操作
這篇文章主要介紹了vue 獲取url參數(shù)、get參數(shù)返回?cái)?shù)組的操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11
vue-resource 攔截器(interceptor)的使用詳解
本篇文章主要介紹了vue-resource 攔截器(interceptor)的使用詳解,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-07-07
Vue用mixin合并重復(fù)代碼的實(shí)現(xiàn)
這篇文章主要介紹了Vue用mixin合并重復(fù)代碼的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11
vue實(shí)現(xiàn)將圖像文件轉(zhuǎn)換為base64
這篇文章主要介紹了vue實(shí)現(xiàn)將圖像文件轉(zhuǎn)換為base64,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02
詳解vuex持久化插件解決瀏覽器刷新數(shù)據(jù)消失問題
這篇文章主要介紹了詳解vuex持久化插件解決瀏覽器刷新數(shù)據(jù)消失問題,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-04-04
Vue-cli3中如何引入ECharts并實(shí)現(xiàn)自適應(yīng)
這篇文章主要介紹了Vue-cli3中如何引入ECharts并實(shí)現(xiàn)自適應(yīng),具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06

