Home  >  Article  >  WeChat Applet  >  Implementation of shopping cart function in WeChat mini program

Implementation of shopping cart function in WeChat mini program

hzc
hzcforward
2020-07-03 11:15:052848browse

Preface

In the past, shopping carts were basically implemented through a large number of DOM operations. The WeChat applet is actually very similar to the usage of vue.js. Next, let’s see how the applet can implement the shopping cart function.

Requirements

First, let’s figure out the needs of the shopping cart.

  • Single selection, all selection and cancellation, and the total price will be calculated according to the selected products

  • The purchase quantity of a single product increases and Reduce

  • Delete items. When the shopping cart is empty, the page will change to the layout of the empty shopping cart

According to the design drawing, we can first implement a static page. Next, let’s look at what kind of data a shopping cart needs.

  • First is a product list (carts). The items in the list need: product image (image), product name (title), unit price (price), quantity (num), Whether it is selected (selected), product id (id)

  • and then select all in the lower left corner, a field (selectAllStatus) is required to indicate whether all are selected

  • The total price in the lower right corner (totalPrice)

  • Finally, you need to know whether the shopping cart is empty (hasList)

I know what I need. Data, we define these first when the page is initialized.

Code implementation

Initialization

Page({
    data: {
        carts:[],               // 购物车列表
        hasList:false,          // 列表是否有数据
        totalPrice:0,           // 总价,初始为0
        selectAllStatus:true    // 全选状态,默认全选
    },
    onShow() {
        this.setData({
          hasList: true,        // 既然有数据了,那设为true吧
          carts:[
            {id:1,title:'新鲜芹菜 半斤',image:'/image/s5.png',num:4,price:0.01,selected:true},
            {id:2,title:'素米 500g',image:'/image/s6.png',num:1,price:0.03,selected:true}
          ]
        });
      },
})

We usually get the shopping cart list data by requesting the server, so we assign values ​​to carts in the life cycle function. I thought about getting the latest status of the shopping cart every time I enter the shopping cart, and onLoad and onReady are only executed once during initialization, so I need to put the request in the onShow function. (Let’s pretend to be some fake data here)

Layout wxml

Repair the static page written before and bind the data.

 <view class="cart-box">
    <!-- wx:for 渲染购物车列表 -->
    <view wx:for="{{carts}}">
    
        <!-- wx:if 是否选择显示不同图标 -->
        <icon wx:if="{{item.selected}}" type="success" color="red" bindtap="selectList" data-index="{{index}}" />
        <icon wx:else type="circle" bindtap="selectList" data-index="{{index}}"/>
        
        <!-- 点击商品图片可跳转到商品详情 -->
        <navigator url="../details/details?id={{item.id}}">
            <image class="cart-thumb" src="{{item.image}}"></image>
        </navigator>
        
        <text>{{item.title}}</text>
        <text>¥{{item.price}}</text>
        
        <!-- 增加减少数量按钮 -->
        <view>
            <text bindtap="minusCount" data-index="{{index}}">-</text>
            <text>{{item.num}}</text>
            <text bindtap="addCount" data-index="{{index}}">+</text>
        </view>
        
        <!-- 删除按钮 -->
        <text bindtap="deleteList" data-index="{{index}}"> × </text>
    </view>
</view>

<!-- 底部操作栏 -->
<view>
    <!-- wx:if 是否全选显示不同图标 -->
    <icon wx:if="{{selectAllStatus}}" type="success_circle" color="#fff" bindtap="selectAll"/>
    <icon wx:else type="circle" color="#fff" bindtap="selectAll"/>
    <text>全选</text>
    
    <!-- 总价 -->
    <text>¥{{totalPrice}}</text>
</view>

Calculate the total price

The total price = the price of the selected product 1* the price of the selected product 2* the quantity...
According to the formula, you can get

getTotalPrice() {
    let carts = this.data.carts;                  // 获取购物车列表
    let total = 0;
    for(let i = 0; i<carts.length; i++) {         // 循环列表得到每个数据
        if(carts[i].selected) {                   // 判断选中才会计算价格
            total += carts[i].num * carts[i].price;     // 所有价格加起来
        }
    }
    this.setData({                                // 最后赋值到data中渲染到页面
        carts: carts,
        totalPrice: total.toFixed(2)
    });
}

Other operations on the page that will cause the total price to change need to call this method.

Selection event

It is selected when clicked, and becomes unselected when clicked again. This is actually changing the selected field. Pass data-index="{{index}}" to pass the index of the current product in the list array to the event.

<p>selectList(e) {<br>    const index = e.currentTarget.dataset.index;    // 获取data- 传进来的index<br>    let carts = this.data.carts;                    // 获取购物车列表<br>    const selected = carts[index].selected;         // 获取当前商品的选中状态<br>    carts[index].selected = !selected;              // 改变状态<br>    this.setData({<br>        carts: carts<br>    });<br>    this.getTotalPrice();                           // 重新获取总价<br>}<br></p>

Select all events

Select all is to change the selected of each product according to the all-selected status selectAllStatus

<p>selectAll(e) {<br>    let selectAllStatus = this.data.selectAllStatus;    // 是否全选状态<br>    selectAllStatus = !selectAllStatus;<br>    let carts = this.data.carts;<br><br>    for (let i = 0; i < carts.length; i++) {<br>        carts[i].selected = selectAllStatus;            // 改变所有商品状态<br>    }<br>    this.setData({<br>        selectAllStatus: selectAllStatus,<br>        carts: carts<br>    });<br>    this.getTotalPrice();                               // 重新获取总价<br>}<br></p>

Increase or decrease the quantity

Click number, Add 1 to num, click the - sign. If num > 1, then subtract 1

<p>// 增加数量<br>addCount(e) {<br>    const index = e.currentTarget.dataset.index;<br>    let carts = this.data.carts;<br>    let num = carts[index].num;<br>    num = num + 1;<br>    carts[index].num = num;<br>    this.setData({<br>      carts: carts<br>    });<br>    this.getTotalPrice();<br>},<br>// 减少数量<br>minusCount(e) {<br>    const index = e.currentTarget.dataset.index;<br>    let carts = this.data.carts;<br>    let num = carts[index].num;<br>    if(num <= 1){<br>      return false;<br>    }<br>    num = num - 1;<br>    carts[index].num = num;<br>    this.setData({<br>      carts: carts<br>    });<br>    this.getTotalPrice();<br>}<br></p>

Delete product

Click the delete button to delete the current element from the shopping cart list. After deletion, if the shopping cart is empty, change the shopping cart empty flag hasList to false

deleteList(e) {
    const index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    carts.splice(index,1);              // 删除购物车列表里这个商品
    this.setData({
        carts: carts
    });
    if(!carts.length){                  // 如果购物车为空
        this.setData({
            hasList: false              // 修改标识为false,显示购物车为空页面
        });
    }else{                              // 如果不为空
        this.getTotalPrice();           // 重新计算总价格
    }   
}

Summary

Although the shopping cart function is relatively simple, there are still many knowledge points involved in the WeChat applet, which is suitable Newbies practice to master.

Recommended tutorial: "WeChat Mini Program"

The above is the detailed content of Implementation of shopping cart function in WeChat mini program. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete