1. Initial applet
1.1. What is an applet
Relying on wechat, a complete application is available at your fingertips.
1.2. Applet registration
Wechat public platform registration: https://mp.weixin.qq.com/
1.3. Install wechat developer tools
Official documents of wechat applet: https://developers.weixin.qq.com/doc/
2. Introduction to applet development Basics
2.1. JSON configuration
2.1.1. Global configuration
(1)app.json
The app.json file in the root directory of the applet is used to globally configure the wechat applet. The content of the file is a JSON object.
Common configuration items:
- entryPagePath
- window
- pages
- tabBar
(2) project.config.json configuration file
(3) sitemap.json configuration file
2.1.2 page configuration
Each applet page can also use. JSON file to configure the window performance of this page. The configuration items in the page will overwrite the same configuration items in the window of app.json on the current page. The file content is a JSON object.
2.2 WXML file
2.2.1 data binding
Declare relevant attributes in the. js file of the current page, for example:
//index.js file Page({ data: { msg: 'hello', }, });
Use in the index.wxml file:
<view>{{msg}}</view>
2.2.2 conditional rendering
Declare relevant attributes in the. js file of the current page, for example:
//index.js file Page({ data: { isShow: false, }, });
Use in the index.wxml file:
<view wx:if="{{isShow}}">hello</view>
2.2.3 list rendering
Declare relevant attributes in the. js file of the current page, for example:
//index.js file Page({ data: { list: ['a', 'b', 'c'], }, });
Use in the index.wxml file:
<view wx:for="{{list}}" wx:key="index">{{index}},{{item}}</view>
2.2.4 template and reference
Declare the template in the. wxml file:
<template name="msgItem"> <view> <text> msg: {{msg}} </text> </view> </template>
Use in the current. wxml file:
<template is="msgItem" data="{{...item}}" />
Where item is the variable declared in the. js file, for example:
//page.js Page({ data: { item: { msg: 'hello', }, }, });
If you want to use the template template of the current page on an external page, you need to import or include. Import can only import the template currently pointing to the file. Include can import not only the template, but also other elements of the target file.
import uses:
<import src="../index/index.wxml" /> <template is="msgItem" data="{{msg: 'forbar'}}" />
include use:
<include src="../index/index.wxml" />
2.2.5 WXS syntax
Write a script in a. wxml document, for example:
<wxs module="abc"> var msg = 'hello abc' module.exports = { msg: msg } </wxs> <view>{{abc.msg}}</view>
You need to understand the syntax of WXS:
- What data types can be used;
- Which statements can be declared;
- How to use operators;
- Declared variables can only use var;
- Modular programming;
2.2.6 event handling
Click bind:tap or bindtap, for example:
index.wxml file:
<view bindtap="onclick" data-id="1">click</view>
Declare the click event function in the index.js file, for example:
Page({ data: {}, onclick(event) { console.log(event.currentTarget.dataset.id); }, });
Using bindtap events will cause bubbles. You can use catchtap to prevent bubbles, for example:
<view catchtap="onclick">click</view>
2.3 WXSS file
WXSS (WeiXin Style Sheets) is a set of style languages used to describe the component styles of WXML. WXSS is used to determine how WXML components should be displayed.
Extensions to CSS:
- rpx for unit size
- Use import to import other style files
3. Advanced applet development
3.1 life cycle
Application lifecycle
Calling App() in the app.js file, the parameter of the function is a Object type, and the life function is defined in the parameter object.
- onLaunch, listen for applet initialization
- onShow, listen for applet startup or switch to the foreground
- onHide, monitor the applet to switch to the background
- onError, error listening function
- onPageNotFound, there is no listening function on the page
Page lifecycle
The Page() is called in the.js file of the page. The parameter of the function is an object type and the life cycle function attribute of the object:
- onLoad, listen for page loading
- onShow, monitor the page display
- onReady, monitor the completion of the first rendering of the page
- onHide, listening page hidden
- onUnload, listen for page unloading
- onPullDownRefresh, listen for user drop-down actions
- onReachBottom, the handler of the bottom pull event on the page
- Onshareaappmessage, forward to wechat friends
- onShareTimeline, forward to circle of friends
- onAddToFavorites, collections
- onPageScroll to monitor the scrolling of the screen
- onResize, monitor page size
- onTabItemTap: click trigger when the current page is a tab page
3.2 route jump
Jump to tab page
wx.switchTab(): jump to the tabBar page and close all other non tabBar pages
Jump to normal page
**wx.redirectTo: * * close the current page and jump to a page in the application. However, it is not allowed to jump to the tabbar page.
**wx.navigateTo: * * keep the current page and jump to a page in the application. But you can't jump to the tabbar page. The page stack in the applet can be up to ten layers.
**wx.navigateBack: * * close the current page and return to the previous page or multi-level page.
Jump to any page
wx.reLaunch(): close all pages and open to a page in the application
Routing parameters
wx.navigateTo({ url: 'page?id=1', });
Receive routing parameters in the onLoad life cycle of the page
Page({ onLoad(options) { console.log(options.id); }, });
3.3 data cache
Synchronous operation
- Save data, wx.setStorageSync()
- Get data, wx.getStorageSync()
- Delete data, wx.removeStorageSync()
- Clear data, wx.clearStorageSync()
Asynchronous operation
- Save data, wx.setStorage(options)
- Get data, wx.getStorage(options)
- Delete data, wx.removeStorage(options)
- Clear data, wx.clearStorage(options)
3.4. Modularization
3.4.1 official components
3.4.2. User defined components
Create a component file in the components directory
Use usingComponents to import components in the. json file of the page
3.4.3 third party components
npm install UI component library
Building npm in applet development tools
3.5 network request
Send an HTT request using wx.request(). The request(option) parameter is an object type. The common parameter object properties are:
- rul, HTTP address of the request
- data, request parameters
- Method, request method
- Success, the callback function that requests success
- Timeout, timeout
3.6 interface interaction
- wx.showToast(), light hint (toast)
- wx.showModal, prompt box
- wx.showLoading, loading prompt box
- wx.showActionSheet, bottom action menu
4. Applet development and expansion
4.1 hardware capability
4.2 cloud development capability
4.2.1 cloud database
Create a cloud database object:
const db = wx.cloud.database();
Select a collection:
db.collection('Set name');
Add data:
db.collection('Set name').add({ data: { Field name: Value, ... }, success: (res)=>{ //Successful callback function } })
Modify data:
//Update individual data db.collection('Set name') .doc(id) .update({ data: { Field name: New value, //Fields to update }, success() {}, }); //Do complex update operations on elements, such as self increment, self multiplication, array addition, etc const c = db.command; db.collection('Set name') .doc(id) .update({ data: { Field name: c.inc(1), //Auto increment of current field }, success() {}, });
Delete data:
//Delete a piece of data db.collection('Set name') .doc(id) .remove({ success() {}, }); //Delete multiple pieces of data // async await syntax is used in cloud functions const cloud = require('wx-server-sdk'); const db = cloud.database(); const _ = db.command; exports.main = async (event, context) => { try { return await db .collection('todos') .where({ done: true, }) .remove(); } catch (e) { console.error(e); } };
Query data:
//Query a single piece of data db.collection('Set name') .doc(id) .get({ success(res) {}, }); //Query multiple items by criteria db.collection('Set name') .where({ _openid: 'xxx', }) .get({ success(res) {}, }); //Query set db.collection('Set name').get({ success(res) {}, }); //Query by Promise db.collection('Set name') .get() .then((res) => {});
4.2.2 cloud storage
Upload file:
//Upload function wx.cloud.uploadFile({ cloudPath: 'example.png', // Path uploaded to the cloud filePath: '', // Applet temporary file path success: (res) => { // Return file ID console.log(res.fileID); }, fail: console.error, }); //Example: upload local album pictures // Let the user select a picture wx.chooseImage({ success: (chooseResult) => { // Upload pictures to cloud storage space wx.cloud.uploadFile({ // Specify the cloud path to upload to cloudPath: 'my-photo.png', // Specifies the applet temporary file path of the file to upload filePath: chooseResult.tempFilePaths[0], // Successful callback success: (res) => { console.log('Upload succeeded', res); }, }); }, });
Download File:
wx.cloud.downloadFile({ fileID: '', // File ID success: (res) => { // Return temporary file path console.log(res.tempFilePath); }, fail: console.error, });
Delete file:
wx.cloud.deleteFile({ fileList: ['a7xzcb'], success: (res) => { // handle success console.log(res.fileList); }, fail: console.error, });
4.2.3 cloud function
Create a cloud function in the applet developer tool. For example, the cloud function name is demo
Example code of cloud function:
// Cloud function entry file const cloud = require('wx-server-sdk'); cloud.init(); // Cloud function entry function exports.main = async (event, context) => { const wxContext = cloud.getWXContext(); return { event, openid: wxContext.OPENID, appid: wxContext.APPID, unionid: wxContext.UNIONID, }; };
Receive external parameters in cloud function:
exports.main = async (event, context) => { //Deconstruct the external parameters. The attribute of the parameter object is {a:xx, b:xx} let { a, b } = event; //Use return to return data to the outside world return { sum: a + b, }; };
Calling cloud functions in small programs:
wx.cloud.callFunction({ name: 'demo', data: { a: 1, b: 2, }, complete: (res) => { //Return result of calling cloud function }, }); //Use Promise to call cloud functions wx.cloud .callFunction({ name: 'demo', data: { a: 1, b: 2, }, }) .then((res) => { //Get the result returned by the cloud function });
4.3. Full stack development capability
Step 1: build the server
Create project
express -e todo cd todo cnpm i
Install database dependencies
cnpm i mongoose --save
Routing design
//Add data http://localhost:3000/todo/add , parameter title route.post('/todo/add'); //Modify data http://localhost:3000/todo/update , parameter title_ id route.post('/todo/update'); //Delete data http://localhost:3000/todo/del , parameters_ id route.get('/todo/del'); //Query a single piece of data http://localhost:3000/todo/find , parameters_ id route.get('/todo/find'); //Query multiple data http://localhost:3000/todo/query , parameter page route.get('/todo/query');
Schema document object design
schema({ title: String, createTime: Number, });
Step 2: build the background management system UI
Installation of scaffold
cnpm i -g @vue/cli
Create project
vue create todo
Installation dependency
cnpm i axios --save cnpm i element-ui --save
Project initialization:
1. The axios module is introduced globally in main.js
import axios from 'axios'; Vue.prototype.$axios = axios;
2. Introduce ElementUI globally in main.js
import ElementUI from 'element-ui'; import 'element-ui/lib/theme-chalk/index.css'; Vue.use(ElementUI);
Step 3: applet development
Create cloud function, sample code
The applet supplements itself
The core parts of the applet are:
I:
(1) Global configuration
(2) Page configuration
2: Cloud development
(1) Cloud database
Small programs provide a cloud database of their own, so that they do not need to build other databases outside themselves, and then call them. They can be built and invoked directly in the database above the small programs.
First, obtain the established database:
const db = wx.cloud.database();
After obtaining the database, perform database related operations through the following methods:
db.collection('Name of the database').where/doc('Conditions, generally openId')/.add/remove/updata/get({ success:(res)=>{ //The arrow function is used here to solve the problem of this pointing console.log(res) } })
(2) Cloud function
The applet also provides the function of cloud function, that is, the code running in the cloud does not need to manage the server. It is written in the development tool, and the back-end code can be run by one click upload and deployment.
First create a cloud function folder in cloudfunctions, write cloud functions in index.js, and throw them out after writing. Then right-click the new cloud function folder and select upload and deploy. Here, you choose not to upload node modules,
Then you can see the uploaded cloud function in the cloud function. Call to see the document
(3) Cloud storage
Cloud development provides a piece of storage space and provides the ability to upload files to the cloud and download files in the cloud with permission management. Developers can use cloud storage functions through API s on the applet side and cloud function side.
Here, upload files or photos to the cloud, and then use them
wx.chooseImage({ // Get local files through this method (that is, open the local folder to find pictures) success: (res) => { //Callback after success console.log(res); console.log(res.tempFilePaths[0]); //Get file address wx.cloud.uploadFile({ //Upload the file to the cloud through this method cloudPath: 'hello.jpg', //File name uploaded to the cloud filePath: res.tempFilePaths[0], //Upload path to cloud success: (res) => { //Callback after successful upload console.log(res.fileID); //Get the returned fileID wx.cloud.downloadFile({ //Download files such as pictures fileID: res.fileID, success: (res) => { //The file will be displayed after the download is successful // console.log(res.tempFilePath); console.log(res.tempFilePath); // console.log(res.tempFilePath) this.setData({ imgUrl: res.tempFilePath, }); }, }); }, }); }, });