


Example code for developing shopping cart in WeChat applet
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.
Summary: Add or subtract product quantity, summarize price, select all or none
Design ideas:
1. Upload from the network into the following Json data format array 1. Shopping cart id: cid 2. Title title 3. Quantity num 4.PictureAddress 5. Price price 6. Subtotal 7. Whether to select selected
2. Click the checkbox toggle operation. If it is already selected, it will become unavailable after clicking. Select, on the contrary, click based on index as the identifier instead of cid, which is convenient for traversal
3. Select all operation The first click will select all, click again to not select all, select all buttonIt also follows 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 the weight of Android.
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 productthumbnail, the upper right is the product title, and the lower right is the product price and quantity. The product quantity is implemented using WXStepper Addition and subtraction operations
js: Initialize a data source, which is often obtained from the network. The related interface can be found at: http://www.php.cn/
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}, ] } })
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>
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; }
wxss to cart.wxss
Copy the contents of stepper.wxml to cart.wxmlDifferent from the previous single component What's important is that the array minusStatus 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']staticCharacter WXStepper replacement Into 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>
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 ? 'disabled' : 'normal'; // 购物车数据 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 ? 'disabled' : 'normal'; // 购物车数据 var carts = this.data.carts; carts[index].num = num; // 按钮可用状态 var minusStatuses = this.data.minusStatuses; minusStatuses[index] = minusStatus; // 将数值与状态写回 this.setData({ carts: carts, minusStatuses: minusStatuses }); },
pass valuejs 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}}"/>
##
/*复选框样式*/ .carts-list icon { margin-top: 60rpx; margin-right: 20rpx; }
Bind click checkboxEvent
, perform an inverse selection operation on the selected 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 }); }
Rendering:
1.4 Add Select All and Settlement Now buttons
1.4. 1 Modify the layout file to align the bottom of the above buttons, 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>
之前用来实现,发现无论如何都不能实现全选部件与结算按钮分散对齐,不响应如下样式
display: flex; flex-direction: row; justify-content: space-between;
样式表
/*底部按钮*/ .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; }
1.4.2 全选与全不选事件
实现bindSelectAll事件,改变全选状态
首先定义一个data值,以记录全选状态
selectedAllStatus: false
事件实现:
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 }); }
1.4.3 立即结算显示目前所选的cid,以供提交到网络,商品数量应该是包括在cid中的,后端设计应该只关注cid与uid
布局文件也埋一下toast,js只要改变toast的显示与否即可。
<toast hidden="{{toastHidden}}" bindchange="bindToastChange"> {{toastStr}} </toast>
为立即结算绑定事件bindCheckout,弹出cid弹窗
bindCheckout: function() { // 初始化toastStr字符串 var toastStr = 'cid:'; // 遍历取出已勾选的cid for (var i = 0; i < this.data.carts.length; i++) { if (this.data.carts[i].selected) { toastStr += this.data.carts[i].cid; toastStr += ' '; } } //存回data this.setData({ toastHidden: false, toastStr: toastStr }); }, bindToastChange: function() { this.setData({ toastHidden: true }); }
1.5 底部悬浮固定
1.5.1 商品列表 .carts-list 加入 margin-bottom: 80rpx; 以及修改上边距为零,使得底部部件与分隔不重复出现,padding: 0 40rpx;
1.5.2 底部按钮 .carts-footer 加入 background: white;
1.5.3 .carts-footer 加入
position: fixed; bottom: 0; border-top: 1px solid #eee;
1.6 汇总
1.6.1 首先定义一个数据源,并在布局文件中埋坑
total: ''
1.6.2 通用汇总函数
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: '¥' + total }); }
然后分别在bindMinus bindPlus bindCheckbox bindSelectAll onLoad中调用this.sum()
如图:
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
The above is the detailed content of Example code for developing shopping cart in WeChat applet. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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;

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

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

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

Use the WeChat applet to achieve the carousel switching effect. The WeChat applet is a lightweight application that is simple and efficient to develop and use. In WeChat mini programs, it is a common requirement to achieve carousel switching effects. This article will introduce how to use the WeChat applet to achieve the carousel switching effect, and give specific code examples. First, add a carousel component to the page file of the WeChat applet. For example, you can use the <swiper> tag to achieve the switching effect of the carousel. In this component, you can pass b

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.

Implementing the sliding delete function in WeChat mini programs requires specific code examples. With the popularity of WeChat mini programs, developers often encounter problems in implementing some common functions during the development process. Among them, the sliding delete function is a common and commonly used functional requirement. This article will introduce in detail how to implement the sliding delete function in the WeChat applet and give specific code examples. 1. Requirements analysis In the WeChat mini program, the implementation of the sliding deletion function involves the following points: List display: To display a list that can be slid and deleted, each list item needs to include

To implement the picture rotation effect in WeChat Mini Program, specific code examples are required. WeChat Mini Program is a lightweight application that provides users with rich functions and a good user experience. In mini programs, developers can use various components and APIs to achieve various effects. Among them, the picture rotation effect is a common animation effect that can add interest and visual effects to the mini program. To achieve image rotation effects in WeChat mini programs, you need to use the animation API provided by the mini program. The following is a specific code example that shows how to
