微信小程序 “萬利商城”實戰之十: 商品列表頁加入購物車功能的實現


加入購物車功能的基本實現是這樣的:

用戶點擊“加入購物車” , 小程序將該商品信息發送到服務器記錄下來,

同時頁面上“加入購物車”的按鈕變成一個輸入框,用戶可以增加/減少商品數量,

當用戶點“購物車” Tabbar時,切換到shoppingcart/shoppingcart.wxml頁面,

此頁面顯示購物車中的商品列表,頁面效果如下 :

接下來我們就來編碼完成加入購物車的功能。

先在index.wxml中加入如下的代碼 ,見紅色部分:

 1 <view class="detail1">
 2     <text>{{index}} {{item.productName}}</text>
 3     <text>{{item.price}}</text>
 4     <text>{{item.originalPrice}}</text>
 5     
 6 <view class="qtyinfo1" wx:if="{{item.inShoppingCart==0}}"> 7 <button class="button1" data-productid="{{item.productId}}" data-index="{{index}}" bindtap="addToShoppingCart">加入購物車</button> 8 </view> 9 <view class="qtyinfo1" wx:else> 10 <text class="minus1" data-productid="{{item.productId}}" data-index="{{index}}" bindtap="tapMinus">-</text> 11 <input class="qty1" type="text" data-productid="{{item.productId}}" data-index="{{index}}" value="{{item.productQty}}" /> 12 <text class="plus1" data-productid="{{item.productId}}" data-index="{{index}}" bindtap="tapPlus">+</text> 13 </view>
14 
15   </view>

  1 . 首先要在productList這個json數組中加入2個字段 “inShoppingCart”和"productQty" ,

“inShoppingCart”用來記錄當前商品是否已經被加入了購物車,"productQty"用來記錄用戶購買的數量。

代碼如下:

 1 var products=[
 2           {'productId':111,'productName':'女裝T恤簡潔11','price':12.9,'originalPrice':22.9,'imageUrl':'../../images/product11.jpg',
 3           'inShoppingCart':0,'productQty':1},
 4           {'productId':122,'productName':'女裝T恤簡潔22','price':15.9,'originalPrice':25.9,'imageUrl':'../../images/product22.jpg',
 5           'inShoppingCart':1,'productQty':1},
 6           {'productId':133,'productName':'女裝T恤簡潔33','price':18.9,'originalPrice':38.9,'imageUrl':'../../images/product33.jpg',
 7           'inShoppingCart':0,'productQty':1},
 8           {'productId':144,'productName':'女裝T恤簡潔44','price':18.9,'originalPrice':38.9,'imageUrl':'../../images/product44.jpg',
 9           'inShoppingCart':0,'productQty':1}
10         ];

 

2 . 當用戶點“加入購物車”按鈕時候要將按鈕隱藏起來,變成可以加減商品數量的控件,所以在index.wxml中需要做一個判斷,

微信小程序在標簽中加判斷用wx:if這個屬性,可以搭配wx:else來使用,這里我們用wx:if="{{item.inShoppingCart==0}}"

做判斷

3 . <button class="button1" data-productid="{{item.productId}}" data-index="{{index}}"

bindtap="addToShoppingCart">加入購物車</button>是一個按鈕控件,

上面定義了一個點擊函數addToShoppingCart,需要在index.js中完成相關邏輯,

data-productid="{{item.productId}}" 是將當前商品的productId值傳給addToShoppingCart 函數,

小程序的傳值非常簡單,任意定義一個變量(這里是productId),在變量前面加上data- 作為屬性,后面放值就可以了。

然后在addToShoppingCart 函數中就可以用下面的方式取值來用:

let productId = options.currentTarget.dataSet.productid; 

4 . <view class="qtyinfo1" wx:else></view>用來顯示一個輸入框和加/減數量的按鈕,讓用戶可以增減商品數量。

5 . bindtap="tapMinus"bindtap="tapPlus" 定義了2個方法tapMinustapPlus

分別對應增加數量和減少數量的操作,我們要在index.js中實現這個邏輯。

data-productid="{{item.productId}}" data-index="{{index}}"是傳遞給函數的值。

 

index.wxss中定義的樣式如下 :

 1 .button1   /*加入購物車按鈕樣式,height和line-height設置成一樣讓文字垂直居中對齊*/ 2 {
 3   height: 80rpx;
 4   line-height: 80rpx;
 5   background-color: antiquewhite;
 6 }
 7 .qtyinfo1    /*加減數量區塊的樣式及標簽布局方式*/
 8 { 
 9   display: flex;
10   flex-direction: row;
11   flex-wrap: nowrap; 
12   margin-left: 60rpx;
13 }
14 .plus1{      /*加數量的樣式*/
15   width: 80rpx;
16   height: 80rpx;
17   line-height: 80rpx;
18   border:solid 4rpx #c0c0c0;
19   border-left: 0;
20   background-color: aquamarine;
21   font-size: 20pt;
22   text-align: center;
23   border-top-right-radius: 20rpx;   /*右上邊框設置成圓角*/
24   border-bottom-right-radius: 20rpx;  /*右下邊框設置成圓角*/
25 }
26 .qty1{
27   width: 120rpx;
28   height: 80rpx;
29   line-height: 80rpx;
30   border:solid 4rpx #c0c0c0;
31   background-color: aquamarine;
32   text-align: center;
33 }
34 .minus1{
35   width: 80rpx;
36   height: 80rpx;
37   line-height: 80rpx;
38   border:solid 4rpx #c0c0c0;
39   border-right:0;
40   background-color: aquamarine;
41   font-size: 20pt;
42   text-align: center;
43   border-top-left-radius: 20rpx;   /*左上邊框設置成圓角*/
44   border-bottom-left-radius: 20rpx;   /*左下邊框設置成圓角*/
45 }

 

index.js中給對應的事件編碼 :

 1   addToShoppingCart: function (options) { 
 2     let productId = options.currentTarget.dataset.productid;
 3     let index = options.currentTarget.dataset.index;
 4 
 5     this.saveShoppingCart(1, index, productId, 1);
 6   },
 7 
 8   tapMinus: function (options) { 
 9     let productId = options.currentTarget.dataset.productid;
10     let index = options.currentTarget.dataset.index;
11 
12     let qty = this.data.productList[index].productQty
13     let newQty = qty-1; 
14     if(newQty<1)
15     {
16       wx.showToast({title: '數量不能小於1!' });
17       return false;
18     }
19  
20     this.saveShoppingCart(2, index, productId, newQty);
21   },
22   tapPlus: function (options) { 
23     let productId = options.currentTarget.dataset.productid;
24     let index = options.currentTarget.dataset.index;
25 
26     let qty = this.data.productList[index].productQty
27     let newQty = qty+1;
28     if(newQty>99)
29     {
30       wx.showToast({title: '數量不能大於99!'});
31       return false;
32     }
33  
34     this.saveShoppingCart(3, index, productId, newQty);
35   },
36 
37   saveShoppingCart: function (operationType, productIndex, productId, productQty) {  
38     var _this=this;
39     wx.request({
40       url: 'http://www.tm.com/webapi/shoppingcart',
41       data:{
42         'operationType':operationType,
43         'productIndex':productIndex,
44         'productId':productId,
45         'productQty':productQty
46       },
47       method:'GET',
48       success:function(res){
49 
50         _this.setData({['productList['+productIndex+'].productQty']:productQty});
51         wx.showToast({title: 'Success'});
52         if (operationType=1)
53         {
54           _this.setData({['productList['+productIndex+'].inShoppingCart']:1});
55         }
56       }
57     })
58   },

 

不論是添加商品到購物車,還是增減購物車中商品數量,都需要將商品信息(包括商品名稱、價格、數量)保存到服務器,

本質上都是對數據庫中商品的數量做的修改,所以我們定義了一個公共的函數

saveShoppingCart: function (operationType, productIndex, productId, productQty) { } 來執行數據庫操作,各個函數說明如下:

加入購物車:

1 addToShoppingCart: function (options) { 
2     let productId = options.currentTarget.dataset.productid;  //獲取index.wxml中 傳遞過來的productId值,注意名稱與data-productId一致
3     let index = options.currentTarget.dataset.index;  //獲取index.wxml中 傳遞過來的index值
4     //將當前商品的索引值 、productId值、數量傳遞到函數中(加入購物車可以理解為商品數量是0+1),然后更新到服務器上處理。
5     this.saveShoppingCart(1, index, productId, 1);  
6   },

 減少商品數量

 1 tapMinus: function (options) { 
 2     let productId = options.currentTarget.dataset.productid;  //獲取index.wxml中 傳遞過來的productId值,注意名稱與data-productId一致
 3     let index = options.currentTarget.dataset.index;  //獲取index.wxml中 傳遞過來的index值
 4     
 5     let qty = this.data.productList[index].productQty;  //抓取當前數量
 6     let newQty = qty-1; //數量-1
 7     if(newQty<1)  //數量小於1時給出提示並終止后面的操作
 8     {
 9       wx.showToast({title: '數量不能小於1!' });
10       return false;
11     }
12     //將當前商品的索引值 、productId值、數量傳遞到函數中,然后更新到服務器上處理。
13     this.saveShoppingCart(2, index, productId, newQty);
14   },

增加商品數量 :

 1 tapPlus: function (options) { 
 2     let productId = options.currentTarget.dataset.productid;  //獲取index.wxml中 傳遞過來的productId值,注意名稱與data-productId一致
 3     let index = options.currentTarget.dataset.index;  //獲取index.wxml中 傳遞過來的index值
 4 
 5     let qty = this.data.productList[index].productQty;  //抓取當前數量
 6     let newQty = qty+1;  //數量+1
 7     if(newQty>99)  //數量大於99時給出提示並終止后面的操作
 8     {
 9       wx.showToast({title: '數量不能大於99!'});
10       return false;
11     }
12     //將當前商品的索引值 、productId值、數量傳遞到函數中,然后更新到服務器上處理。
13     this.saveShoppingCart(3, index, productId, newQty);
14   },

 更新服務器 :

 1 saveShoppingCart: function (operationType, productIndex, productId, productQty) {  
 2     var _this=this;
 3     wx.request({
 4       url: 'http://www.tm.com/webapi/shoppingcart',
 5       data:{  //將服務器需要的數據都傳遞過去,實際項目可以根據需要加其他的參數
 6         'operationType':operationType,
 7         'productIndex':productIndex,
 8         'productId':productId,
 9         'productQty':productQty
10       },
11       method:'GET',
12       success:function(res){
13         //服務器更新成功就用setData()函數將數量設置到該商品的輸入框中, 只有調用此函數頁面的值才會變化,
14         _this.setData({['productList['+productIndex+'].productQty']:productQty});
15         wx.showToast({title: 'Success'});
16         if (operationType=1)
17         {//點加入購物車的按鈕時需要用setData()函數更新inShoppingCart的值,按鈕就會變成加減和輸入框,讓用戶知道購買了此商品並可以去修改數量
18           _this.setData({['productList['+productIndex+'].inShoppingCart']:1});
19         }
20       }
21     })
22   },

 至此,添加商品到購物車的功能就完成了, 在服務器端需要設計一個購物車表 ,基本結構如下 :

字段 說明
product_id 商品編號
product_qty 購買數量
shoppingcart_key 購物車編號,多個商品加入購物車的時候這個值是相同的
add_time 創建時間
add_user 創建人

 

 服務器端的代碼在介紹后端開發的時候單獨講,這里略過。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM