Home WeChat Applet Mini Program Development Simple example of shopping cart in WeChat mini program

Simple example of shopping cart in WeChat mini program

Jun 22, 2018 pm 04:04 PM
WeChat applet shopping cart Shopping cart implementation

This article mainly introduces relevant information about a simple example of the WeChat mini program shopping cart. Friends who need it can refer to

WeChat mini program. Here is a small demo that implements the shopping cart function. If you need this function Friends can refer to it.

Abstract: Add or subtract product quantity, summarize price, select all or none

Design ideas:

1. From the Internet Upload the array in the following Json data format 1. Shopping cart id: cid 2. Title title 3. Quantity num 4. Image address 5. Price price 6. Subtotal 7. Whether selected

is selected 2. Click Repeat If the marquee toggle operation is already selected, it will become unselected by clicking. On the contrary, the click will be based on index as the identifier instead of cid, which facilitates traversal

3. Select all operation The first click will select all, and then click again Click to unselect all, and the select all button itself will also follow the toggle transformation

4. Click the settlement button to take out the selected cid array for submission to the server through the network. Here is a toast as a demonstration of the result. .

5. Use stepper to perform addition and subtraction operations, also use index as the identifier, and write back the num value after clicking.

6. Layout, select all and align with the bottom of the checkout button, the shopping cart mall adaptive height, similar to Android weight.

Steps:

Initial data rendering

1.1 Layout and style sheet

The top is a product list, and the bottom It is a select all button and an immediate settlement button

The left part of the product list is the product thumbnail, the upper right is the product title, and the lower right is the product price and quantity. The product quantity uses WXStepper to implement addition and subtraction operations

js: Initialize a data source, which is often obtained from the network. For related interfaces, see: https://mp.weixin.qq.com/debug/wxadoc/dev/api/network-request.html

Page({
  data:{
    carts: [
      {cid:1008,title:'Zippo打火机',image:'https://img12.360buyimg.com/n7/jfs/t2584/348/1423193442/572601/ae464607/573d5eb3N45589898.jpg',num:'1',price:'198.0',sum:'198.0',selected:true},
      {cid:1012,title:'iPhone7 Plus',image:'https://img13.360buyimg.com/n7/jfs/t3235/100/1618018440/139400/44fd706e/57d11c33N5cd57490.jpg',num:'1',price:'7188.0',sum:'7188.0',selected:true},
      {cid:1031,title:'得力订书机',image:'https://img10.360buyimg.com/n7/jfs/t2005/172/380624319/93846/b51b5345/5604bc5eN956aa615.jpg',num:'3',price:'15.0',sum:'45.0',selected:false},
      {cid:1054,title:'康师傅妙芙蛋糕',image:'https://img14.360buyimg.com/n7/jfs/t2614/323/914471624/300618/d60b89b6/572af106Nea021684.jpg',num:'2',price:'15.2',sum:'30.4',selected:false},
      {cid:1063,title:'英雄钢笔',image:'https://img10.360buyimg.com/n7/jfs/t1636/60/1264801432/53355/bb6a3fd1/55c180ddNbe50ad4a.jpg',num:'1',price:'122.0',sum:'122.0',selected:true},
    ]
  }
})
Copy after login

Layout file

<view class="container carts-list">
  <view wx:for="{{carts}}" class="carts-item" data-title="{{item.title}}" data-url="{{item.url}}" bindtap="bindViewTap">
    <view>
     <image class="carts-image" src="{{item.image}}" mode="aspectFill"/>
    </view>
   <view class="carts-text">
    <text class="carts-title">{{item.title}}</text>
    <view class="carts-subtitle">
     <text class="carts-price">{{item.sum}}</text>
     <text>WXStepper</text>
    </view>
   </view>
  </view>
</view>
Copy after login

Style sheet

/*外部容器*/
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
} 

/*整体列表*/
.carts-list {
  display: flex;
  flex-direction: column;
  padding: 20rpx 40rpx;
}

/*每行单元格*/
.carts-item {
  display: flex;
  flex-direction: row;
  height:150rpx;
  /*width属性解决标题文字太短而缩略图偏移*/
  width:100%;
  border-bottom: 1px solid #eee;
  padding: 30rpx 0;
}

/*左部图片*/
.carts-image {
  width:150rpx;
  height:150rpx;
}


/*右部描述*/
.carts-text {
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

/*右上部分标题*/
.carts-title {
  margin: 10rpx;
  font-size: 30rpx;
}

/*右下部分价格与数量*/
.carts-subtitle {
  font-size: 25rpx;
  color:darkgray;
  padding: 0 20rpx;
  display: flex;
  flex-direction: row;
  justify-content:space-between;
}

/*价格*/
.carts-price {
  color: #f60;
}
Copy after login


1.2 Integrate WXStepper

1.2.1 Copy component content

[2016-10-16]

Copy the content of stepper.wxss to cart.wxss

Copy the contents of stepper.wxml to cart.wxml

The difference from the previous single component is that the array minusStatuses needs to be defined here to correspond to each plus and minus button. Of course, there is no problem in merging it into carts.

       minusStatuses: ['disabled', 'disabled', 'normal', 'normal', 'disabled']

The original static character WXStepper is replaced with the following code

 <view class="stepper">
        <!-- 减号 -->
        <text class="{{minusStatuses[index]}}" data-index="{{index}}" bindtap="bindMinus">-</text>
        <!-- 数值 -->
        <input type="number" bindchange="bindManual" value="{{item.num}}" />
        <!-- 加号 -->
        <text class="normal" data-index="{{index}}" bindtap="bindPlus">+</text>
       </view>
Copy after login

js code bindMinus and bindPlus are transformed as follows:

bindMinus: function(e) {
    var index = parseInt(e.currentTarget.dataset.index);
    var num = this.data.carts[index].num;
    // 如果只有1件了,就不允许再减了
    if (num > 1) {
      num --;
    }
    // 只有大于一件的时候,才能normal状态,否则disable状态
    var minusStatus = num <= 1 ? &#39;disabled&#39; : &#39;normal&#39;;
    // 购物车数据
    var carts = this.data.carts;
    carts[index].num = num;
    // 按钮可用状态
    var minusStatuses = this.data.minusStatuses;
    minusStatuses[index] = minusStatus;
    // 将数值与状态写回
    this.setData({
      carts: carts,
      minusStatuses: minusStatuses
    });
  },
  bindPlus: function(e) {
    var index = parseInt(e.currentTarget.dataset.index);
    var num = this.data.carts[index].num;
    // 自增
    num ++;
    // 只有大于一件的时候,才能normal状态,否则disable状态
    var minusStatus = num <= 1 ? &#39;disabled&#39; : &#39;normal&#39;;
    // 购物车数据
    var carts = this.data.carts;
    carts[index].num = num;
    // 按钮可用状态
    var minusStatuses = this.data.minusStatuses;
    minusStatuses[index] = minusStatus;
    // 将数值与状态写回
    this.setData({
      carts: carts,
      minusStatuses: minusStatuses
    });
  },
Copy after login

The effect is as shown:

##[2016-10-17]

Correction of saving the number of manual changes to an array

1.3 Integrating LXCheckboxGroup

Copy the layout file code to wxml. Here you need to judge the selected status. Generally, the shopping cart check status is recorded in Network.

The index value is used to pass value js and used for traversal.

 <!-- 复选框图标 -->
    <icon wx:if="{{item.selected}}" type="success_circle" size="20" bindtap="bindCheckbox" data-index="{{index}}"/>
    <icon wx:else type="circle" size="20" bindtap="bindCheckbox" data-index="{{index}}"/>
Copy after login

The check box is centered

/*复选框样式*/
.carts-list icon {
  margin-top: 60rpx;
  margin-right: 20rpx;
}
Copy after login

Bind the click check box event to invert the selection state.

  bindCheckbox: function(e) {
    /*绑定点击事件,将checkbox样式改变为选中与非选中*/
    //拿到下标值,以在carts作遍历指示用
    var index = parseInt(e.currentTarget.dataset.index);
    //原始的icon状态
    var selected = this.data.carts[index].selected;
    var carts = this.data.carts;
    // 对勾选状态取反
    carts[index].selected = !selected;
    // 写回经点击修改后的数组
    this.setData({
      carts: carts
    });
  }
Copy after login

Rendering:


1.4 Add select all and immediate settlement buttons

1.4.1 Modify the layout file to achieve The above buttons are aligned at the bottom, using flex and fixed height.

Reduce it to 3 lines to see if it is still at the bottom; in addition, make sure it is suspended at the bottom and will not be scrolled by the scrolling of the list items.

 <view class="carts-footer">
    <view bindtap="bindSelectAll">
      <icon wx:if="{{selectedAllStatus}}" type="success_circle" size="20"/>
      <icon wx:else type="circle" size="20" />
      <text>全选</text>
    </view>
    <view class="button">立即结算</view>
  </view>
Copy after login

I used before, but I found that it was impossible to achieve dispersed alignment of all selected components and the settlement button, and it did not respond to the following styles

  display: flex;
  flex-direction: row;
  justify-content: space-between;
Copy after login

Style Table

/*底部按钮*/
.carts-footer {
  width: 100%;
  height: 80rpx;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

/*复选框*/
.carts-footer icon {
  margin-left: 20rpx;
}

/*全选字样*/
.carts-footer text {
  font-size: 30rpx;
  margin-left: 8rpx;
  line-height: 10rpx;
}

/*立即结算按钮*/
.carts-footer .button {
  line-height: 80rpx;
  text-align: center;
  width:220rpx;
  height: 80rpx;
  background-color: #f60;
  color: white;
  font-size: 36rpx;
  border-radius: 0;
  border: 0;
}
Copy after login

1.4.2 Select all and unselect all events

Implement the bindSelectAll event and change the all-selected state

First define a data value to record the all-selected state

selectedAllStatus: false


Event implementation:

 bindSelectAll: function() {
    // 环境中目前已选状态
    var selectedAllStatus = this.data.selectedAllStatus;
    // 取反操作
    selectedAllStatus = !selectedAllStatus;
    // 购物车数据,关键是处理selected值
    var carts = this.data.carts;
    // 遍历
    for (var i = 0; i < carts.length; i++) {
      carts[i].selected = selectedAllStatus;
    }
    this.setData({
      selectedAllStatus: selectedAllStatus,
      carts: carts
    });
  }
Copy after login

1.4.3 Immediate settlement displays the currently selected cid for When submitted to the Internet, the product quantity should be included in the cid. The back-end design should only focus on the cid and uid

The layout file should also bury the toast. JS only needs to change the display of the toast.

<toast hidden="{{toastHidden}}" bindchange="bindToastChange">
  {{toastStr}}
</toast>
Copy after login

Bind the event bindCheckout for immediate settlement and pop up the cid pop-up window

 bindCheckout: function() {
    // 初始化toastStr字符串
    var toastStr = &#39;cid:&#39;;
    // 遍历取出已勾选的cid
    for (var i = 0; i < this.data.carts.length; i++) {
      if (this.data.carts[i].selected) {
        toastStr += this.data.carts[i].cid;
        toastStr += &#39; &#39;;
      }
    }
    //存回data
    this.setData({
      toastHidden: false,
      toastStr: toastStr
    });
  },
  bindToastChange: function() {
    this.setData({
      toastHidden: true
    });
  }
Copy after login

1.5 Bottom floating fixed

1.5.1 Product list.carts-list Add margin-bottom: 80rpx; and modify the top margin to zero so that the bottom components and separation do not appear repeatedly. Padding: 0 40rpx;

1.5.2 Bottom button.carts-footer Add background: white;

1.5 .3 .carts-footer join

  position: fixed;
  bottom: 0;
  border-top: 1px solid #eee;
Copy after login

##1.6 Summary

1.6.1 First define a data source and bury it in the layout file

total: ''

{{total}}

1.6.2 General summary function

sum: function() {
    var carts = this.data.carts;
    // 计算总金额
    var total = 0;
    for (var i = 0; i < carts.length; i++) {
      if (carts[i].selected) {
        total += carts[i].num * carts[i].price;
      }
    }
    // 写回经点击修改后的数组
    this.setData({
      carts: carts,
      total: &#39;¥&#39; + total
    });
  }
Copy after login

Then bindMinus This.sum() is called in bindPlus bindCheckbox bindSelectAll onLoad

As shown in the figure:

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:

WeChat mini program makes takeout menu ordering function

How to implement it in the development of WeChat mini program E-commerce shopping cart logic

The above is the detailed content of Simple example of shopping cart 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1262
29
C# Tutorial
1235
24
Xianyu WeChat mini program officially launched Xianyu WeChat mini program officially launched Feb 10, 2024 pm 10:39 PM

Xianyu's official WeChat mini program has quietly been launched. In the mini program, you can post private messages to communicate with buyers/sellers, view personal information and orders, search for items, etc. If you are curious about what the Xianyu WeChat mini program is called, take a look now. What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3. If you want to use it, you must activate WeChat payment before you can purchase it;

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? The shopping cart is an important feature of an online store, which allows users to add items they want to purchase to the shopping cart and manage the items. In Java, we can implement a simple shopping cart function by using object-oriented approach. First, we need to define a product category. This class contains attributes such as product name, price, and quantity, as well as corresponding Getter and Setter methods. For example: publicclassProduct

Practical tutorial: Detailed explanation of shopping cart function with PHP and MySQL Practical tutorial: Detailed explanation of shopping cart function with PHP and MySQL Mar 15, 2024 pm 12:27 PM

Practical tutorial: Detailed explanation of the shopping cart function with PHP and MySQL. The shopping cart function is one of the common functions in website development. Through the shopping cart, users can easily add the goods they want to buy to the shopping cart, and then proceed with settlement and payment. In this article, we will detail how to implement a simple shopping cart function using PHP and MySQL and provide specific code examples. To create a database and data table, you first need to create a data table in the MySQL database to store product information. The following is a simple data table

Implement image filter effects in WeChat mini programs Implement image filter effects in WeChat mini programs Nov 21, 2023 pm 06:22 PM

Implementing picture filter effects in WeChat mini programs With the popularity of social media applications, people are increasingly fond of applying filter effects to photos to enhance the artistic effect and attractiveness of the photos. Picture filter effects can also be implemented in WeChat mini programs, providing users with more interesting and creative photo editing functions. This article will introduce how to implement image filter effects in WeChat mini programs and provide specific code examples. First, we need to use the canvas component in the WeChat applet to load and edit images. The canvas component can be used on the page

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

To implement the drop-down menu effect in WeChat Mini Programs, specific code examples are required. With the popularity of mobile Internet, WeChat Mini Programs have become an important part of Internet development, and more and more people have begun to pay attention to and use WeChat Mini Programs. The development of WeChat mini programs is simpler and faster than traditional APP development, but it also requires mastering certain development skills. In the development of WeChat mini programs, drop-down menus are a common UI component, achieving a better user experience. This article will introduce in detail how to implement the drop-down menu effect in the WeChat applet and provide practical

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

WeChat applet implements picture upload function With the development of mobile Internet, WeChat applet has become an indispensable part of people's lives. WeChat mini programs not only provide a wealth of application scenarios, but also support developer-defined functions, including image upload functions. This article will introduce how to implement the image upload function in the WeChat applet and provide specific code examples. 1. Preparatory work Before starting to write code, we need to download and install the WeChat developer tools and register as a WeChat developer. At the same time, you also need to understand WeChat

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

The official WeChat mini program of Xianyu has been quietly launched. It provides users with a convenient platform that allows you to easily publish and trade idle items. In the mini program, you can communicate with buyers or sellers via private messages, view personal information and orders, and search for the items you want. So what exactly is Xianyu called in the WeChat mini program? This tutorial guide will introduce it to you in detail. Users who want to know, please follow this article and continue reading! What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3.

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? With the rapid development of e-commerce, shopping carts have become an important part of online malls. The shopping cart is used to save the products purchased by users and related information, providing users with a convenient and fast shopping experience. Designing a reasonable shopping cart table structure in MySQL can help developers store and manage shopping cart data effectively. This article will introduce how to design the shopping cart table structure of the mall in MySQL and provide some specific code examples. First, the shopping cart table should contain

See all articles