Introduction to the
Wechat mini program is a kind of application that can be used without download and installation. It realizes the dream of application “at your fingertips”. Users can open the application by scanning or searching it.
Small programs are part of the wechat ecosystem, which provides a more convenient and efficient way of user interaction.
benefits
- User convenience
- Common APP we need to use the process: understand APP – download – open – register – use
- Applet version of the APP use process: Learn about APP – open (scan/search) – use
-
Free up the phone’s memory space
- For people who don’t have much space on their phones, installing a lot of apps can be a disaster, often facing a lack of space
- Small programs do not need to be installed and have a specified size (currently no more than 8M, including when using subcontracting)
-
Make the mobile desktop more concise
- No need to download an App, no need to spend time managing your own App
-
One end of development, multi-terminal running (iOS end, Android end), and the bottom can call a variety of native interfaces
Preparation: Apply for an APPID
Log on to the wechat public platform to apply
- Each account corresponds to a small program
- Enterprises, governments, media and other organizations can register 50 mini-programs
- Self-employed and individual type subjects can register 5 applets
- Each individual business owner and individual type entity can have two free storage development space of the cloud
Applets composition
-
Page Layout — WXML (similar to HTML)
-
Page style — WXSS (similar to CSS, some not supported, some enhanced)
-
Page Script — JavaScript + WXS (WeixinScript)
App. json -- Global configuration file
{
// All applet pages need to be registered here
// Each entry in the array is the path address of the corresponding PAGE's JSON file
"pages": [
// The first item of the array is loaded as the home page of the entire applet
"pages/home/home"."pages/about/about"]}Copy the code
Early experience
Data binding
<! In WXML, there are two basic container components view <-> div text <-> span -->
<view>
<! Mustache syntax for binding data in WXML
{{ msg }}
</view>
Copy the code
// For each Page, the Page function is called and the configuration object is passed
// For the App component, call the App function and pass the configuration object
// When parsing, the applet will automatically create the corresponding Page instance or App instance
Page({
// Define the page state in the data option
// Note: this is an object, not a function. When the applet creates the instance, data is not placed on the prototype of the component instance as vue does
data: {
msg: 'Hello World'}})Copy the code
To iterate over
<! -- wx:for is a loop instruction provided by the applet -->
<! -- wx:for (string) -- wx:for (string)
<view wx:for="{{ users }}" wx:key="name">
<! -- item is each item of the loop --> applet provides a variable by default -->
{{ item.name }} --- {{ item.age }}
</view>
Copy the code
event
<view>
{{ counter }}
</view>
<! -- Buttondesize property can adjust the size of the button, default width is 100% -->
<! Mustache mustache mustache is never needed for event binding, only for attribute value binding -->
<button size="mini" bindtap="handleTap" >+</button>
Copy the code
Page({
data: {
counter: 0
},
// Define the corresponding event response function directly in the configuration object
handleTap() {
// Just like React, the interface will be updated after the setData function is called
// Note: this is setData, not setState
this.setData({
counter: this.data.counter + 1})}})Copy the code
mvvm
Applets use an MVVM model similar to VUE, and the ViewModel is the Applets native Sister MINA framework
Why is MVVM useful?
- DOM Listeners can bind DOM Listeners to the Model layer
- Data Bindings: ViewModel layer can respond Data variables to View layer
The MVVM architecture moves us from imperative to declarative programming
configuration
Many of the development requirements for applets are specified in configuration files
- Doing so can be more beneficial to our development efficiency
- And you can ensure that some of the style of the development of the small program is relatively consistent
In applets, there are four main configuration files
The file name | function |
---|---|
project.config.json | Project profiles, such as project name, appID, and so on, are similar topackage.json .jsconfig.json .tsconfig.json The function of theTo uniformly configure the behavior and execution environment of the editor (especially in collaborative development) Default does not need to change, if need to change in the small program IDE details to configure, project.config.json Will update synchronously |
sitemap.json | By default, the applet turns on the search function This means that wechat will use crawlers to set up search indexes for our small programs to improve their exposure If some of our pages do not need to be crawled by wechat crawlers, we can modify this file |
app.json | Global configuration file |
page.json | Page configuration file Each page has its own separate page configuration file |
Global configuration
There are a lot of global configurations, and we’ll take a few more important ones here. Check out the full official documentation
Pages: indicates the page path list
- Used to specify which pages the applet consists of, each corresponding to a page path (including file name) information
- All pages in the applet must be registered in Pages
Window: global default window display
"window": {
// Navigation background color -- only HexColor is supported
"navigationBarBackgroundColor": "#ff5777"./ / navigation text color - white | black
"navigationBarTextStyle": "white".// Navigation bar title
"navigationBarTitleText": "Applets".// The background color of the drop-down list
"backgroundColor": "#f2f4f5"./ / a drop-down list of loading color - dark | light
"backgroundTextStyle": "dark".// Whether to allow pull-down refresh -- ios allows pull-down refresh by default, Android does not allow pull-down refresh by default
"enablePullDownRefresh": true
}
Copy the code
TabBar: Display of the bottom TAB bar
"tabBar": {
// The selected color is TAB
"selectedColor": "#ff5777".// Bottom TAB list with number of [2, 5]
// Only parts of the page registered in the list array will have tabs
// If a page is not registered in the list array, there is no TAB bar at the bottom of the page
"list": [{// Jump path
"pagePath": "pages/home/home".// Display text
"text": "Home page".// Image path
"iconPath": "assets/tabbar/home.png".// Select the image path
"selectedIconPath": "assets/tabbar/home_active.png"
},
{
"pagePath": "pages/profile/profile"."text": "Settings"."iconPath": "assets/tabbar/profile.png"."selectedIconPath": "assets/tabbar/profile_active.png"}}]Copy the code
Configuration page
Each applet page can also use a.json file to configure the window appearance of the page
The configuration items in the page overwrite the same configuration items in the window of app.json on the current page
{
"usingComponents": {},
// Note: the configuration here is a top-level configuration option, not a Windows sub-configuration option
"navigationBarTitleText": "Classification"."enablePullDownRefresh": false
}
Copy the code
Two-thread model
The host environment of the small program is the wechat client
The host environment provides a two-threaded model for the execution of various files of applets: WXML files, WXSS files, JS files
- The WXML module and WXSS style run in the render layer, which renders with WebView threads (a program with multiple pages will cause multiple WebView threads).
- JS scripts (app.js/home.js, etc.) run in the logical layer, which uses JsCore to run JS scripts (sandbox environment runs JS code, not allowed to execute any browser-specific interface, such as page hopping, DOM manipulation, etc.).
- Both threads will transfer and interact through wechat client (Native)
WXML and DOM tree
WXML is equivalent to a DOM tree and can also be simulated using a JS object, which is what we call a virtual DOM object
Initialize render
WXML can be converted into JS objects (virtual DOM trees) and then rendered into real DOM trees
Data changes
Change MSG data from “Hello World” to “Goodbye” using setData
- The node corresponding to the generated JS object will change
- At this point, you can compare the two JS objects to get the changed part – DOM Diff algorithm
- This difference is then applied to the original Dom tree
- To update the UI, this is how ** “data driven” ** works
The overall flow of interface rendering
-
At the rendering layer, the host environment converts WXML into the corresponding JS object;
-
Turn the JS object into a real DOM tree and render it by the render layer thread.
-
When data changes, the logical layer provides the latest change data, and the CHANGES of JS objects are compared for diFF algorithm comparison.
-
Reflect the latest changes to the real DOM tree and update the UI;
Applets start process
App life cycle function
Each applet needs to register the applet sample by calling the app method in app.js
At registration time, you can bind the corresponding lifecycle functions, in which the corresponding code is executed
// Call the App method to register the App component
App({
// The function that is executed when the page initialization is complete
// When a small program exits the background for 2 hours, it is always there, and the process is not killed
// If you enter the applet again, the onShow method will be executed, but the onLanch method will not be executed
onLaunch() {
console.log('Page initialization')
// User information can be obtained here
wx.getUserInfo({
success(res) {
console.log(res)
}
})
},
onShow() {
console.log('Interface display')},onHide() {
console.log('Hide interface')},onError() {
console.log('Interface error')}})Copy the code
All the things you do in your App
- The common opening scenarios are as follows: open in group chat session, open in the list of small programs, open with a swipe of wechat, and open another small program
In the onLaunch and onShow lifecycle callbacks, there is the options parameter, which has the scene value, which can be used to determine the scene value entered by the applet
App({
onLaunch(options) {
console.log(options.scene)
},
onShow(options) {
console.log(options.scene)
}
})
Copy the code
- Monitor life cycle functions and execute corresponding business logic in the life cycle, such as obtaining wechat user information in a life cycle function
Ways to obtain basic information of wechat users:
-
wx.getUserInfo
wx.getUserInfo({ success(res) { console.log(res) } }) Copy the code
-
Button component – Change open-type to getUserInfo and bind the bindGetUserInfo event to get it
<button
open-type="getUserInfo"
bindgetuserinfo="handleUserInfo"
size="mini"
>
click me
</button>
Copy the code
Page({
handleUserInfo(e) {
console.log(e.detail.userInfo)
}
})
Copy the code
- Display user information using the open-data component – note: display, not fetch
<open-data type="userNickName" />
<! The result of this display is a picture -->
<open-data type="userAvatarUrl" />
Copy the code
- Because there is only one instance of App() and it is globally shared (singleton), we can put some shared data here
// App.js
App({
// The name of the key is custom, but is generally called globalData
globalData: {
username: 'Klaus'.age: 24}})// home.js
The getApp method gets the instance object of the App component
const app = getApp()
console.log(app.globalData)
Copy the code
Page life cycle function
You can bind the corresponding life cycle function in the page.js of each Page, and in the life cycle function, the corresponding code is executed
Page({
// Listen for page loading
onLoad() {
console.log('onLoad')},// The page is displayed
onShow() {
// The value of this in the lifecycle is the current Page instance
console.log(this)
console.log('onShow')},// It was rendered for the first time
onReady() {
console.log('onReady')},// The page is hidden
onHide() {
console.log('onHide')},// Unmount the page
onUnload() {
console.log('onUnload')}})Copy the code
Common operations in Page
- Send a network request in a lifecycle function to fetch data from the server;
- Initialize some data for presentation by WXML reference
- Listen for events in WXML and bind the corresponding event function
- Other listeners (page scrolling, pull-up refresh, pull-down load more, etc.)
Page({
// Initialize the data
data: {
user: {}},onShow() {
// A network request occurred
wx.request({
// 1. By default, all requested interfaces in applets need to be configured on the console (web side), otherwise they will not be able to request
// 2. In the process of development, for the convenience of debugging, you can temporarily disable the verification of legitimate domain names in the details TAB, then the network request can occur normally
url: 'http://httpbin.org/get?name=klaus&age=23'.The success method recommends using the arrow function for definition
// If defined using the arrow function, this inside is the current Page instance
// If you use the normal function definition, this is undefined (because there is no globalThis inside the applet).
success: res= > {
// console.log(this)
// The specific data obtained can be viewed in the AppData TAB of the applets development tool
this.setData({
user: res.data.args
})
}
})
},
// Bind custom events
handleTap() {
// This in a custom event is still the Page instance
console.log(this)},// Built-in events
onPageScroll(detail) {
console.log(detail.scrollTop)
},
onReachBottom() {
console.log('Hit the bottom')},onPullDownRefresh() {
console.log('Pull refresh')}})Copy the code
,