当前位置:网站首页>Applet development summary
Applet development summary
2022-07-02 10:06:00 【IronKee】
Wechat applet
Recently, I am developing a new small program , It should also be the last project I am responsible for in this company , Mainly made shopping carts place order Product details page home page Promotional advertising pages, etc
Record some development summaries
First wx.request Need to encapsulate , Login also needs to be encapsulated
Secondly, from the perspective of architecture , Common modules and functions need to be extracted
For example, the address list address component is used in the member center and the submit order page , Need to be drawn into components
Address selection component used in shopping cart and product details pages , Need to be drawn into components
And the home page Promotional advertising page Extra cars used in the order page , Then you need to write a public car addition js
As well as submitting the order page and the second payment of the order are used to pay , Need to write a payment js
encapsulation wx.request
use promise encapsulation wx.request
return new Promise((resolve, reject) => {
wx.request({
url: OPTIOIN.url,
method: OPTIOIN.method,
dataType: "json",
header: {
...OPTIOIN.header,
Cookie: loginCookies,
"Content-Type": OPTIOIN.contentType,
},
data: OPTIOIN.params,
success: async function ({
data, errMsg, statusCode, header = {
} }) {
if (statusCode == 200) {
resolve(data);
} else {
reject(errMsg);
}
},
fail: function (res) {
wx.showToast({
title: " Network anomalies , Please try again later !",
icon: "none",
});
reject(res);
},
});
});
encapsulation request According to the needs of the project , To determine header Whether cache is needed , Do you need to set cookie, There's more http Error code processing , such as 500,302 And so on can be handled here
Set up a safe area
adapter iphonex And above
padding-bottom: calc(100rpx + constant(safe-area-inset-bottom));
padding-bottom: calc(100rpx + env(safe-area-inset-bottom));
ios11 New properties ,constant compatible IOS<11.2,env compatible IOS>11.2
Use... In applets less
Use less It's more convenient
stay xx.wxss New in the same directory xx.less file ,vscode Install plug-ins in Easy LESS, It will compile automatically when saving wxss file
The navigation bar
The navigation bar supports clicking to jump to the corresponding area , Support scrolling to the corresponding area to follow the change
<!-- The navigation bar -->
<view class="nav-content" style="background:rgba(255,255,255,{
{
tabOpacity}});padding-top: {
{
navTop}}px;">
<view class="tab-bar" style="opacity:{
{
tabOpacity}}">
<view class="tab-item {
{selectIndex == item.num ? 'tab-select' : ''}} {
{index==0?'tab-item-first':''}}" wx:for="{
{tabBarList}}" wx:key="index" bindtap="jumpTo" data-num="{
{item.num}}" data-area="{
{item.area}}">
{
{item.title}}
<view class="tab-line"></view>
</view>
</view>
</view>
// After rendering the page , Record graphic details and after-sales location of packaging
// Record graphic details 、 After sales packaging top value
calTop(){
const {
tabBarList } = this.data;
tabBarList.forEach((item)=>{
const query = this.createSelectorQuery();
query.select('#'+item.area).boundingClientRect();
query.exec(function (res) {
if (res[0] && res[0].top) {
item.top = res[0].top;
}
});
})
this.setData({
tabBarList})
},
// Page scrolling , The judgment is greater than 150 after , Show navigation bar , At the same time, judge the scrolling distance to the corresponding area and change the selected subscript
// Page scrolling Events onPageScroll Add anti shake
// onPageScroll: debounce(function (event) {
onPageScroll (event) {
const {
scrollTop } = event;
if (scrollTop > 150) {
this.setData({
tabOpacity: 1, scrollTop })
} else {
this.setData({
tabOpacity: 0, scrollTop })
}
// Back to tabbar Subscript
let {
tabBarList, selectIndex } = this.data;
let _scrollTop = scrollTop+400;
if(_scrollTop>tabBarList[1].top){
selectIndex = 2 // Select package after sales
}else{
selectIndex = 1 // Select graphic details
}
this.setData({
selectIndex})
},
// }, 200),
// Click on tab Column jump
jumpTo(e) {
let {
num } = e.currentTarget.dataset
const {
tabBarList } = this.data;
this.setData({
selectIndex: num
})
wx.pageScrollTo({
scrollTop: tabBarList[num-1].top-110
})
},
onReachBottom
The applet has a handler for the bottom pull event on the page onReachBottom
When pulled up to the bottom, it will trigger onReachBottom Function to perform the corresponding action . In other words, the applet comes with a function that can capture the user's bottom event . We no longer need to capture user events
Execute within the component onPageScroll perhaps onReachBottom
onPageScroll onReachBottom All are page In the method , How to use it in the component
//page
onPageScroll (e) {
this.selectComponent("#floor-water") && this.selectComponent("#floor-water").pageScroll(e);
},
onReachBottom (e) {
this.selectComponent("#floor-water") && this.selectComponent("#floor-water").reachBottom(e);
},
//component
pageScroll (e) {
// Processing logic
},
reachBottom (e) {
// Processing logic
},
Select the component to call the method in the component
scrollView
Click to switch , Automatically scroll to the edge area and leak the next
When you click on the new super spring product , Leak out the next , Let users know that there are categories behind , The same goes for clicking forward
// Set it during initialization id
lifetimes: {
attached: function () {
let navList = this.data.floorData;
navList.forEach((item,index)=>{
item.id = 'id'+index
})
this.setData({
navList,
});
}
},
<scroll-view wx:else class="goods-nav goods-nav-static" scroll-x="true" scroll-into-view="{
{activeNavId}}">
<view id="{
{item.id}}" class="goods-nav-item {
{index == activeNavIdx ? 'on' : ''}}" wx:for="{
{navList}}" wx:key="index" bindtap="checkNav" data-item="{
{item}}" data-idx="{
{index}}">{
{item.name}}</view>
</scroll-view>
scroll-into-view attribute
// Switch categories
checkNav (e) {
const {
item, idx} = e.currentTarget.dataset;
const {
activeNavId, activeNavIdx, navList } = this.data;
let _activeNavId = activeNavId;
// Judge whether the first and last tabs are clicked , Other cases , Focus on the previous click , Ensure that there is exposure before and after
if(idx+1 == navList.length){
_activeNavId = navList[navList.length-1].id
}else if(idx == 0){
_activeNavId = 'id0'
}else if(idx>activeNavIdx || idx<activeNavIdx){
_activeNavId = navList[idx-1].id
}
this.setData({
activeNavIdx: idx,
activeNavId: _activeNavId,
});
},
Applet payment
If the payment function is required in the applet , That encapsulates a payment js It's necessary to
import API from '../api/index';
const wxPay = function (param) {
return new Promise((resolve, reject) => {
// Call the server to get the payment parameters
API.pay.payOrder(param).then((payOrder)=>{
let payForm = JSON.parse(payOrder.resStr)
wx.requestPayment({
timeStamp: payForm.timeStamp || '',
nonceStr: payForm.nonceStr || '',
package: payForm.package || '',
signType: 'MD5',
paySign: payForm.paySign || '',
success (res) {
if (res.errMsg === 'requestPayment:ok') {
wx.showToast({
icon: 'none',
title: ' Successful payment ',
})
}
resolve(payOrder)
},
fail (res) {
wx.showToast({
icon: 'none',
title: ' Failure to pay ',
})
reject(payOrder)
}
});
}).catch((e)=>{
console.log(e)
wx.showToast({
icon: 'none',
title: ' Payment order failed , Please try again later ',
})
})
})
}
module.exports = {
wxPay,
}
utilize map duplicate removal
Some promotional information , The same promotional offer returns multiple , Only take the first of its kind , duplicate removal
// duplicate removal
let map = new Map()
promotion.activityList = promotion.activityList.filter((item) => {
return !map.has(item.activityType) && map.set(item.activityType, 1)
})
split array
Some interfaces only support query at a time 20 Data
// Query promotion information Check at most once 20 individual
let productsList = [' Suppose its length is 100'];
let productsListAll = [];
// Press 20 20 Split
if(productsList.length){
for(var i=0,len=productsList.length;i<len;i+=20){
productsListAll.push(productsList.slice(i,i+20));
}
}
// Cycle call
productsListAll.forEach(async (item)=>{
let params = {
productsList: item,
}
const promotions = await API.goods.promotionsTags(params);
if(promotions){
// Processing data
}
console.log(goodsList)
this.setData({
goodsList})
})
To be continued , Keep adding …
边栏推荐
- Read Day6 30 minutes before going to bed every day_ Day6_ Date_ Calendar_ LocalDate_ TimeStamp_ LocalTime
- C language: making barrels
- 2837xd code generation - Supplement (3)
- QT QLabel样式设置
- Read 30 minutes before going to bed every day_ day3_ Files
- How does {} prevent SQL injection? What is its underlying principle?
- What is call / cc- What is call/cc?
- Share a blog (water blog)
- Personal experience & blog status
- Junit4运行mvn test 测试套件升级方案
猜你喜欢
随机推荐
It is the most difficult to teach AI to play iron fist frame by frame. Now arcade game lovers have something
Brief analysis of edgedb architecture
Image recognition - Data Cleaning
Read Day6 30 minutes before going to bed every day_ Day6_ Date_ Calendar_ LocalDate_ TimeStamp_ LocalTime
三相并网逆变器PI控制——离网模式
2837xd code generation module learning (3) -- IIC, ECAN, SCI, watchdog, ECAP modules
[illusory] weapon slot: pick up weapons
2837xd代码生成模块学习(2)——ADC、ePWM模块、Timer0
2837xd 代码生成——StateFlow(1)
vs+qt 设置应用程序图标
What is call / cc- What is call/cc?
QT信号槽总结-connect函数错误用法
Attack and defense world web advanced area unserialize3
2837xd 代码生成——StateFlow(4)
图像识别-数据标注
2837xd 代碼生成——補充(1)
Binary and decimal system of C language
2837xd 代码生成——StateFlow(3)
[illusory] automatic door blueprint notes
三相逆变器离网控制——PR控制