Home WeChat Applet Mini Program Development Implementation of shopping cart function in WeChat mini program

Implementation of shopping cart function in WeChat mini program

Jun 27, 2018 am 10:42 AM
WeChat applet shopping cart

This article mainly introduces the relevant information of the shopping cart function of the WeChat applet in detail. It has certain reference value. Interested friends can refer to it

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 requires.

  • 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)

Know In order to need these data, we first define these when initializing the page.

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}
     ]
    });
   },
})
Copy after login

We usually get the shopping cart list data by requesting the server, so we put it in the life cycle function to assign values ​​to carts. 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

Fix 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>
Copy after login

Calculate total price

Total price = price of selected product 1* Price of selected product 2* 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)
  });
}
Copy after login

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

Selection event

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

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

Select all event

Select all is to change according to the select all status selectAllStatus Selected

selectAll(e) {
  let selectAllStatus = this.data.selectAllStatus;  // 是否全选状态
  selectAllStatus = !selectAllStatus;
  let carts = this.data.carts;

  for (let i = 0; i < carts.length; i++) {
    carts[i].selected = selectAllStatus;      // 改变所有商品状态
  }
  this.setData({
    selectAllStatus: selectAllStatus,
    carts: carts
  });
  this.getTotalPrice();                // 重新获取总价
}
Copy after login

increase and decrease quantity of each product

Click number, num increases 1. Click the - sign. If num > 1, then subtract 1

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

Delete product

Click the delete button to delete the current element from the shopping cart list. If the shopping cart is empty after deletion, 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();      // 重新计算总价格
  }  
}
Copy after login

Summary

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

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

Tools required for WeChat mini program shopping mall system development

Shopping cart in WeChat mini program Simple example

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Xianyu WeChat mini program officially launched Xianyu WeChat mini program officially launched Feb 10, 2024 pm 10:39 PM

Xianyu WeChat mini program officially launched

How to implement a simple shopping cart function in Java? How to implement a simple shopping cart function in Java? Nov 02, 2023 am 11:56 AM

How to implement a simple shopping cart function in Java?

WeChat applet implements image upload function WeChat applet implements image upload function Nov 21, 2023 am 09:08 AM

WeChat applet implements image upload function

What is the name of Xianyu WeChat applet? What is the name of Xianyu WeChat applet? Feb 27, 2024 pm 01:11 PM

What is the name of Xianyu WeChat applet?

How to design the shopping cart table structure of the mall in MySQL? How to design the shopping cart table structure of the mall in MySQL? Oct 30, 2023 pm 02:12 PM

How to design the shopping cart table structure of the mall in MySQL?

Implement the drop-down menu effect in WeChat applet Implement the drop-down menu effect in WeChat applet Nov 21, 2023 pm 03:03 PM

Implement the drop-down menu effect in WeChat applet

Use WeChat applet to achieve carousel switching effect Use WeChat applet to achieve carousel switching effect Nov 21, 2023 pm 05:59 PM

Use WeChat applet to achieve carousel switching effect

How to use PHP to develop the second-hand transaction function of WeChat applet? How to use PHP to develop the second-hand transaction function of WeChat applet? Oct 27, 2023 pm 05:15 PM

How to use PHP to develop the second-hand transaction function of WeChat applet?

See all articles