Small program basic operation summary

Dimension unit

When the screen width is equal to 750px, 1px = 1rpx

When the screen width is equal to 375px, 1px =0.5rpx

Style import only supports relative paths

Built in components

**view tag * * is equivalent to div tag

Text tags can be nested. Text tags can be copied by long pressing text

image tag * * the size of the package online cannot exceed 2M. When using pictures, the pictures on the Internet shall be used uniformly

  The picture has the default width and height (320) px * 240px)

The pictures in the applet directly support lazy loading

Lazy load will judge by itself that when the picture appears in the upper and lower three screens of the viewport, it will start loading the picture by itself

swiper label rotation chart

<swiper autoplay interval="1000" circular indicator-dots>
    // The default width and height of the picture is 320 * 240

	<swiper-item><image model="widthFix" src="" /></image></swiper-item>

</swiper>

Rich text (rich text tag, parsing string into corresponding tag, equivalent to v-html)

// 1 label string
<rich-text nodes="{{ html }}"></rich-text>

// 2 object array
<rich-text nodes="{{ html.model }}"></rich-text>

Button button

Size (size:mini/default), color (type:default/primary/warn), hollowed out (plain),

Is there loading (loading) and development capability (opentype) in front of the text

opentype:

concat directly opens the customer service dialogue function, which needs to be configured in the background of the applet

(change the appid of the applet from the test number to your own appid, log in to the official website of wechat applet, and add customer service wechat)

share forwards the current applet to wechat friends. You can't forward the applet to the circle of friends

getPhoneNumber obtains the mobile phone number of the current user and uses it in combination with events. It is not the applet account of the enterprise. It does not have permission to obtain the mobile phone number of the user

getUserInfo gets the user's personal information

launchApp directly opens the app in the applet

openSetting opens the built-in authorization page of the applet, and only the permissions clicked by the user will appear

Feedback opens the built-in feedback page of the applet

Radio radio box

<radio-group bindchange="handleChange">
	<radio color="red" value="male">male</radio>
    <radio color="red" value="female">female</radio>
</radio-group>
<view>Selected are: {{ gender }} </view>

data: {
	gender: ""
},
handleChange(e) {
	// Gets the value selected in the radio box
	let gender = e.detail.value;
	// Assign the value to the data in data
	this.setData({
		gender // Equivalent to gender: Gender
	})
}


checkbox multiple selection box

<checkbox-group bindchange="handleChange">
	<checkbox value="{{ item.value }}" wx:for="{{ list }}" wx:key="id">{{ item.name }}</checkbox>      
</checkbox-group>
<view>Selected are: {{ checkedList }} </view>

checkedList:[]
handleChange(e) {
	let checkedList = e.detail.value;
	this.setData({
		checkedList
	})
}


Parent component passes value to child component

Passed through the attributes of the tag:

Parent component delivery

Sub component reception

Component({
    // It stores the data to be received from the parent component
    properties: {
        // The name of the data to accept
        aaa:{
            //Type the type of data received
            type: String,
            //value default
            value: ""
        }
    }
});

The child component uses the data passed from the parent component

Use the received data as the data in the data itself

{{ aaa }}

The child component passes values to the parent component

Passed through events.

eg:tab switch bar, click switch.

  1. Binding click events need to be bound in methods

  2. Get the clicked index

  3. Get original array

  4. Loop over array

  5. When the click event is triggered, the user-defined event in the parent component will be triggered and passed to the parent component at the same time

this. Trigger event ("name of custom event of parent component", parameter to be passed)

On the Tabs page:

<view 
      wx:for="{{tabs}}" 
      wx:key="id" 
      class="title_item {{item.isActive?'active':''}}"
      bindtap="hanldeItemTap"
      data-index="{{index}}"
>{{ item.name }}</view>

<view class="tabs_content">
    // The parameters passed by the placeholder are replaced 
	<slot></slot>
</view>

In the js file of the sub component:

methods: {
    hanldeItemTap(e) {
        // Get index
        const {index} = e.currentTarget.dataset;
        // let {tabs} = this.data;
        // tabs.forEach((v,i) => i===index?v.isActive=true:v.isActive=false);
        // Modify data in data
        // this.setData({
        //    tabs
        // })
        
        // Trigger the custom event in the parent component and pass it to the parent component at the same time
        this.triggerEvent("itemChange", {
            index
        })
    }
}

To add a custom event to a custom component in a parent component:

<Tabs binditemChange="handleItemChange">
	<block wx:if="{{tabs[0].isActive}}">1</block>
    <block wx:if="{{tabs[1].isActive}}">2</block>
    <block wx:else>3</block>
</Tabs>

In js of parent component:

data: {
    tabs: [
        {
            id: 1,
            name: "home page",
            isActive: true
        },
        {
            id: 2,
            name: "To be shipped",
            isActive: false
        },
        {
            id: 3,
            name: "Pending payment",
            isActive: false
        }
    ]
}

// A custom event receives the data passed by the subcomponent
handleItemChange(e) {
    // Receive passed parameters
    const {index} = e.detail;
    // Get the original array
    let {tabs} = this.data;
    tabs.forEach((v,i) => i===index?v.isActive=true:v.isActive=false);
    // Modify data in data
    this.setData({
        tabs
    })
}

Third party framework of applet

  1. Tencent wepy is similar to vue

  2. Meituan mpvue is similar to vue

  3. JD taro is similar to react

  4. Didi chameleon

  5. Uni app is similar to vue

  6. Native framework MINA

Initialization of page style

Note: wildcards (*) are not supported in applets

On app Wxss file

page,view,text,swiper,swiper-item,image,navigator {
	padding: 0;
	margin: 0;
	box-sizing: border-box;
}


/*
	Theme color
	1. less There are variables in
	2. Native css and wxss also support css
*/
page {
	--themeColor: #eb4500;
	// When the design draft size is 375px, 1px = 2rpx,14px = 28rpx
	font-size: 28rpx;
}

Use theme colors:

view {
	color: var(--themeColor);
}

Solve the problem of callback to hell (promise of es6)

Create index. In the request folder of the project JS file

It is used by encapsulating methods and then calling functions to pass parameters

// Number of times asynchronous code was sent at the same time
let ajaxTime=0;
export const request=(params) => {
    ajaxTime++;
    // Data loading effect
    wx.showLoding({
       title: "Loading",
        mask: true
    });
    return new Promise((resolve, reject) => {
        wx.request({
            // Parameters passed by deconstruction
            ...params,
            success: (result) => {
                resolve(result);
            },
            faile: (err) => {
            	reject(err);
        	},
            // This function is called regardless of success or failure
            complete: () => {
                ajaxTime--;
                if(ajaxTime === 0) {
                   // Turn off waiting icons
                	wx.hideLoading();
                }                
            }
        });
    });
}

Use the encapsulated request method:

//  Import package file (Note: be sure to complete the path)
import { request } from '../../request/index.js';  // The encapsulated request function is introduced here

Page({
    data: {
        swiperList: []
    },
    // Page load event
    onLoad: function() {
        /*
        	1. Send asynchronous request to get the data used
        */
        /*
            wx.request({
                url: '',  // Interface address
                success: (result) => {
                    // The request succeeded in assigning a value to the swiperList array
                    this.setData({
                        swiperList: result.data.message
                    })
                }

            });
        */
        /*
        	wx.request Too many asynchronous requests will cause the problem of callback hell
        	
        	Solution: promise in es6
        */
        
        // Call method
        this.getSwiperList();
        
    },
    // Call the encapsulated method
    getSwiperList() {
        //  The data filled in here will replace the params,
        request({ url: 'htltps://api/zbtbs/home/swiperList'}); 
        //  Data acquisition succeeded
        .then (result => {
            this.setData({
                swiperList: result.data.message
            })
        });
    }
})


Get locally stored data

In applet:

  Storage method: wx.setStorageSync("key", "value");

  Acquisition method: wx.getStorageSync("key", "value");

There is no data type conversion

Define public url

In request JS file, encapsulating the request method

export const request=(params) => {
    // Define public url
    const baseUrl = "https://api.zbsb.cn/api/public"
    return new Promise((resolve, reject) => {
        wx.request({
            // Parameters passed by deconstruction
            ...params,
            url: baseUrl + params.url;
            success: (result) => {
                resolve(result);
            },
            faile: (err) => {
            	reject(err);
        	}
        });
    });
}

Applet url transfer parameter

// Transfer parameters
<navigator wx:for="Cates" wx:for-item="item" wx:for-index="index" wx:key="id" url="/pages/goods/index?cid={{item.cid}}"></navigator>

// Take parameters
onLoad: function(options) {
	consol.log(options);  // Value of printout options
}

Scroll bar bottoming event (page up sliding event)

Scroll to the bottom of the page to load data

Total pages = math Ceil (total number / number of data displayed per page)

// Get product data list
async getGoodsList() {
    const res=await request({url:"/goods/search",data:this.QueryParams});
    // Get the total number of entries
    const total = res.total;
    // Calculate total pages
    this.totalPage = Math.ceil(total / this.QueryParams.pagesize);
    // Splice array
    this.setData({
        goodsList: [...this.data.goodsList,...res.goods]
    });
    // Close the drop-down refresh window
    wx-stopDownRefresh();
}
// Scroll bar bottoming event
onReachBottom() {
    // Determine whether there is data on the next page
    if(this.QueryParams.pagenum >= this.totalPage) {
        // Current page number > total pages no next page
        
    }
    else {
        // There is also the current page number of the next page + + resend the request data. After the request comes back, the array in data should be spliced
        this.QueryParams.pagenum++;
        this.getGoodsList();
    }
}

Drop down refresh page

  1. Trigger the pull-down refresh event (a configuration item needs to be opened in the json file of the page) [enablePullDownRefresh: true,backgroundTextStyle: dark]

  2. Reset data array

  3. Reset page number to 1

  4. Resend request

  5. The data request is successful. Manually close the waiting effect

onPullDownRefresh() {
    // Reset data array
    this.setData({
        goodsList: []
    });
    // Reset page number to 1
     this.QueryParams.pagenum=1;
    // Resend request
    this.getGoodsList();
}

Delete in js

cart.splice(index, 1);  // Delete the element with index

cart.filter(v => v.checked);  // Pick out the value checked as true in the cart array

Pop up window packaging

In asyncwx JS file

export const showModel=({content}) => {
    return new Promise((resolve,reject) => {
        wx.showModel({
            title: 'Tips',
            content: content,
            success :(res) > {
                resolve(res);
            },
            fail :(err) => {
                reject(err);
            }
        })
    })
}

use

import {showModel} from '../../utils/asyncWx.js';

async showTips() {
    const res=await showModel({content: 'Do you want to delete?'})
    if(res.confirm) {
       cart.splice(index, 1);
        this.setData(cart);
    }
}

Wechat payment

1. Enterprise account number

    A white list must be added to the developer in the applet background of the enterprise account

    One AppID Can bind multiple developers

2. After binding, the developer has the permission of the developer

3. Payment button

First judge whether there is a token in the cache

Did not jump to the authorization page to get the user's token value

Have you performed payment operations

Process: create order, prepare advance payment, initiate wechat payment and query order

**One acquisition token**

handleOrderPay() {
   try {
        // 1. Judge whether there is a token value in the cache
        const token = wx.getStorageSync("token");
        // 2. Judgment
        if(!token) {
            // Jump to authorization page
            wx.navigateTo({
                url: "/page/auth/index"
            })
            return;
        }
        // 3. Create order
        // Prepare the parameters needed to create the order
        const header = {Authorization:token};
        // Prepare request body parameters
        const order_price = this.data.totalPrice;   // Total order price
        const consignee = this.data.address.all;  // Detailed address
        let goods = [];
        const cart = this.data.cart;
        goods.forEach(v => goods.push({
            goods_Id: v.goods_Id, // id of the item
            goods_number: v.goods_number, //Quantity of goods
            goods_price: v.goods_price  // Unit price of goods
        }))
        const orderParams = {order_price,consignee,goods}
        // 4. Prepare to send a request to create an order and obtain the order number
        const {order_number}=await request({url: 				     "/order/create"},method:"POST",data:orderParams,head:head});
        // 5. Initiate advance payment interface
        const {pay}=await request({url:"/order/req_unifiedorder",method:"POST",head,data:{order_number}});
        // 6. Initiate wechat payment
        await requestPayment(pay);
        // 7. Check whether the background order status is successful
        const res=await request(url:"/orders/chkOrder",method:"POST",head,data:{order_number}});
		// Prompt payment success
		await showToast({title:"Payment successful"});
		// Manually delete the data of successfully paid shopping cart in the cache
		let newCart = wx.getStorageSync("cart");
		// Filter out unselected data
		newCart = newCart.filter(v => !v.checked);
		wx.setStorageSync("cart",newCart);
		// 8. Payment succeeded, jump to the order page
		wx.navigateTo({
            url: '/page/order/index'
        })
   } catch(err) {
       await showToast({title:"Payment failure"});
   }
    
}

page/autn/index: obtain authorization

<button open-type="getUserInfo" bindgetUserInfo="handleGetUserInfo">
    Obtain authorization
</button>


// Get user information
// encryptedData  
// rawData
// iv
// signature
async handleGetUserInfo(e) {
    try {
        // Get user information
        const { encryptedData,rawData,iv,signature } = e.detail;
        // Get the token value after applet login in asyncwx Encapsulating token request method in JS
        // wx.login({
        //     timeout: 1000,
        //    success: (result) => {
        //     	cost { code } = result;   
        //    }
        // })
        const {code} = await login();
        const loginParams = { encryptedData, rawData, iv, signature, code }
        // Send a request to get the user's token
        const {token}=await request(url: '/user/wxlogin',data: loginParams,methods: 		"post");
        // Store the obtained token in the cache and jump back to the previous interface at the same time
        wx.getStroageSync("token", token);
        wx.navigateBack({
            data: 1 // Return to the previous level
        })    
    } catch(err) {
    	console.log(err);
    }
}

In asyncwx Package payment method in JS file:

export const requestPayment=(pay) => {
    return new Promise((resolve,reject){
    	wx.request({
           ...pay,
           success: (result) => {
        		resolve(result);
    	   },
           fail: (err) => {
               reject(err);
           }
        })                   
    })
}

2, Prepare advance payment (get parameter pay)

3, Initiate wechat payment (submit pay parameters)

4, Query order

5, Delete the selected purchased goods in the cache

6, The deleted shopping cart data will be cached

7, Jump page

Project release

Note: before publishing, remember to close the illegal domain name verification in the details interface

The size of each uploaded file shall not exceed 2M, and the total size shall not exceed 10M

Upload:

Version number

First number (update of large version)

Second number (important function update)

The third number (minimum function, small bug, small patch)

less files will not be packaged and uploaded

The successfully uploaded applet is also an experience version applet. If you need to turn the experience version applet into an online version applet,

The small program of the experience book that will be submitted on the wechat public platform will be submitted for review (the review time is about one hour).

Tags: Mini Program

Posted by jerr0 on Mon, 09 May 2022 22:11:03 +0300