Introduction to the Application of Wechat Widget Program

Wechat applet is introduced from the following aspects

  • What are small programs? How to build a small program?
  • Page structure of applets?
  • View layer structure, etc?
  • How do components communicate?
  • What are the ways of page skipping?
  • Life cycle?
  • How do widgets introduce other ui components?

Small procedures

What is it?

Wechat program, short for small program, abbreviated as XCX, English name mini program, is an application that can be used without downloading and installing. It realizes the dream of "accessible" application, and users can open the application by sweeping or searching. It also embodies the concept of "run-out" and users do not need to worry about whether to install too many applications. Applications will be ubiquitous and readily available without installation or uninstallation.

How to build a small program? Page structure?

1. Download first Developer Tools

2. The page structure is as follows

  • App() must be registered in app.js and cannot register more than one.

  • Each page needs to be registered manually in app.json, otherwise it cannot be accessed.

  • The first item of pages array in app.json represents the initial page of the applet. Adding/reducing pages in the applet requires modification of pages array.

  • Modifying directly is invalid and cannot change the state of the page. setData is required.

  • The tabBar can only be configured with at least two or at most five tabs in the order of arrays.

  • There are no cookie s, no window s variables, no a tag links, and no iframe s to nest.

3. The main body is composed of three files, app.js, app.json and app.wxss, which are placed in the root directory.

  • app.js
    app.js in the root directory is useful because variables or methods registered within it can be accessed by all pages. It can monitor and process the life cycle of the applet and declare global variables. The rest of the.Js files can get their instances through var app = getApp(), calling the methods and variables defined therein, but not the lifecycle methods.

  • app.json is the global configuration of applets

pages configuration widget composition page, the first page representing the initial page of the widget window settings widget status bar, Title bar, navigation bar, window background color tabBar configuration widget tab bar style and corresponding page

"pages": [ //Setting the path of the page
  "pages/index/index", //No need to write index.wxml,index.js,index,wxss, the framework will automatically find and integrate
"window": { //Setting the presentation of default Windows
  "navigationBarBackgroundColor": "#ffffff ",//Top Navigation Bar Background Color
  "navigationBarTextStyle": "black", //The color black/white of the top navigation text
  "navigationBarTitleText": "Demonstration of Wechat Interface Function", //Display text for top navigation
  "backgroundColor": "#The background color of the eeeeee ",//window"
  "backgroundTextStyle": "light", //Drop-down background font, loading graph style, only support dark/light
  "enablePullDownRefresh": "false", //Whether to support drop-down refresh, if not, do not write directly!
  "disableScroll": true, //  Setting true cannot scroll up and down, true/false, notice! It can only be valid in page.json, but cannot be set in app.json.
"tabBar": { //The performance of the bottom tab or the top tab is an array with at least two configurations and at most five.
  "list": [{ //Set tab attributes, at least 2, up to 5
    "pagePath": "pages/index/index", //Click on the bottom tab to jump the path
    "text": "home page", //Text on tab button
    "iconPath": "../img/a.png", //Path of tab image
    "selectedIconPath": "../img/a.png" //tab is on the current page, which is the path of the selected state
  }, {
    "pagePath": "pages/logs/logs",
    "text": "Journal"
  "color": "red", //The font color of tab
  "selectedColor": "#673ab7 "// The color of the tab on the current page, that is, the selected page's
  "backgroundColor": "#Background of 2196f3", //tab"
  "borderStyle": "white", //Border color black/white
  "position": "bottom" //The top/bottom position of tab in the window
"networkTimeout": { //The default is 60,000 seconds a minute.
    "request": 10000, //Request network timeout time 10,000 seconds
    "downloadFile": 10000, //Link Server Timeout 10000 seconds
      "uploadFile": "10000", //Upload picture 10000 seconds
    "downloadFile": "10000" //10,000 seconds overtime for downloading pictures
"debug": true //When the project is online, it is recommended that this item be closed or not written.
  • app.wxss is a common style sheet for applets that can be used directly in other. wxss files

4. pages folder

The pages folder is the pages of the applet. Each interface is generally composed of four files:. wxml,. wxss,. js,. json. The four files must have the same name and path.

  • js is the script code of the page, registering the page through the Page() function. You can specify the page's initial data, lifecycle, event handling, and so on.

  • wxml is the layout file of the page and can only use components defined by Wechat.

  • wxss is a stylesheet and needs to be noted

1. Unit of Size: rpx can be adapted to the wide bandwidth of the screen

2. Style import: @import import import export style sheet, such as: @import "test.wxss";

3. The global style defined in app.wxss acts on each page. The.Wxss file defined in the page acts only on the corresponding page and overrides the same selector in app.wxss

  • JSON is the configuration file of the page. It can only set the content of windows configuration in app.json, and it will override the same configuration items of windows in app.json.

5. utils file

utils contains some common code extraction js files, which are easy to use as modules. Modules expose to the outside world through module.exports

  • Use elsewhere is var utils = require('... ... / Utls/util.js') for reference
//Declaring methods in util
import UmfLog from '../utils/UmfLog';
 * Debugging tools
class DebugUtils {
     * Initialize load configuration information
    initConfig() {
        UmfLog.error("[DEBUG]Initialization Debugging Tool");
        UmfLog.error("[DEBUG]Warning: Please close the debugging environment in the production environment");
        //Initialization environment


let debugUtils = new DebugUtils();
module.exports = debugUtils;
//Called on other pages
import DebugUtils from './utils/DebugUtils';
     init: function() {
    //Initialize debugging tools (production environment cannot open debugging tools)
    if (DebugUtils.isDebug()) {

View layer WXML

1. Data binding

So how does the Wechat applet manage view and object binding?

  • Data flow is one-way, i.e. view changes do not affect object state
  • Dynamic data in.wxml comes from data in Page. Data binding uses data binding to wrap variables in double braces, which can act on content, component attributes (which need to be in double quotes), control attributes (which need to be in double quotes), and keywords (which need to be in double quotes).
<view class='item item-{{myclass===true?"red":"blue"}}'>

2. What instructions do you have?

  • wx:for loop
<view class='item item-{{myclass===true?"red":"blue"}}'>
    <view wx:for="{{myAry}}" >
      {{index}}: {{}}--{{item.value}}
    <view wx:for="{{myAry}}" wx:for-index="ind" wx:for-item="items">
      {{ind}}: {{}}--{{items.value}}
  • Wx: if wx: elif wx: else hidden condition rendering
//When hidden is true, the dom structure is still wx:if true, it is not.
<view hidden="{{status ? true : false}}"> Hidden </view>
<view wx:if="{{num > 6}}"> </view>

3. ajax requests

wx.request() method can be referred to wx official api

      url: 'url',
      method: "GET",
      header: {
        'content-type': 'json'
      success(res) {

Communication between components

For reference wx official api



  "component": true,
  "usingComponents": {}


<view class='template-child'>
  <block wx:for='{{dataFromParent}}'>
    <button data-id='{{}}' bindtap='onTapChild'>{{}}</button>


   * List of properties of components
  properties: {
    dataFromParent: {
      type: Array,
      value: [],
      observer: function (newVal, oldVal, changedPath) {
        // Functions executed when attributes are changed (optional) can also be written as method name strings defined in the methods section
        // Usually newVal is the newly set data and oldVal is the old data.

   * Initial data of components
  data: { },

   * Method List of Components
  methods: {

    onTapChild: function(event){

      // detail object, provided to event listener function
      var myEventDetail = {
      // Options to trigger events
      var myEventOption = {} 
      // Use the triggerEvent method to trigger custom component events, specifying event names, detail objects, and event options
      this.triggerEvent('parentEvent', myEventDetail, myEventOption)



  "usingComponents": {
    "child": "../component/child/child"


// You can use bind:parentEvent or bindparentEvent 
<view class='parent-wrap'>
  <view> Here is the parent container, data FromParent is the data passed to the child component, and parentEvent is the triggerable event name of the custom component </view>.
  <child dataFromParent='{{contents}}' bind:parentEvent='onParentEvent'/>



   * Initial data of pages
  data: {
    contents: [
        id: 1,
        name: 'Click on the first button'
        id: 2,
        name: 'Click on the second button'

  // When a custom component triggers a parentEvent event, the onParentEvent method is called
  onParentEvent: function (event) {
    // A detail object provided when a custom component triggers an event to retrieve data passed by a subcomponent
    var id = event.detail.tag;
    console.log('Data passed by subcomponents id:', id);
    // Other operations...

Page Jump Mode

(1) Label jump can be referred to navigator

<navigator url="/page/navigate/navigate?title=navigate" open-type="switchTab" hover-class="navigator-hover">Jump to a new page</navigator>
  • app-id Sets the APPID of the applet to jump

  • The path configuration jumps to the page

  • extra-data can set the data to be carried

  • Version is the version of the applet to be opened

  • The open-type attributes of navigator can be selected as `navigate', `redirect', `switchTab', which corresponds to the functions of wx.navigateTo, wx.redirectTo, wx.switchTab.

  • open-type="navigate" is equivalent to the API's wx.navigateTo and wx.navigateTo's url is the path of non-tabBar pages in applications that need to jump.

  • open-type="redirect" is equivalent to the API's wx.redirectTo, and the url of wx.redirectTo is the path of non-tabBar pages in applications that need to jump.

  • open-type="switchTab" is equivalent to the API's wx.switchTab and wx.switchTab's url needs to jump to the tabBar page and close all other non-tabBar pages.

  • When the last switchTab event triggered, all the previous pages were closed.

(2)wx.navigateTo method jump (from the jumped page back to the url page)

Page a

// a.wxml binding jump function
   <image bindtap="bindViewTap" class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"></image>
 //Event Handler
  bindViewTap: function() {
    var id =; 
      url: '../logs/logs?id='+id

b page

//b.js Page Receive Parameters
  onLoad: function (options) { //options are used to receive parameters passed from the previous page
    console.log('options==', options)//options== {id: "2"}
    this.setData({//this.setData method is used to convert the passed id into a widget template language
      logs: (wx.getStorageSync('logs') || []).map(log => {
        return util.formatTime(new Date(log))

(3) The wx.switchTab method jump is only applicable to pages with tabbar settings.

url: 'pages/index/index'

(4)wx.redirectTo method jump to close the current page and jump to a page

 url: 'pages/a/a'

(5)wx.reLaunch method jump to close all open pages and jump to a page

 url: 'pages/a/a'

(6) The wx. navigateBack method returns to the parent page and can be returned at multiple levels.

 //If there are three pages of A, B and C in C page navigateBack, it will return to A page.
3 wx.navigateBack({
4 delta: 2 //The series of jumps
5 })

life cycle

Usually refers to the process of creating, starting, pausing, arousing, stopping and uninstalling programs. The life cycle of applets can be divided into application life cycle and page life cycle.

1. Application Life Cycle

The application life cycle refers to the process of initial loading, method and final destruction of the applet itself.

1. For the first time, the user opens the applet and triggers onLaunch, which is used to monitor the initialization of the applet. It only triggers once in the whole application life cycle.

2. After initialization, the onShow Monitor Widget display is triggered. When the widget starts or enters the foreground display from the background, the onShow will be triggered.

3. Small programs use the foreground to enter the background and trigger the onHide method.

4. Small programs will be destroyed if they are allowed in the background for a certain period of time or if the system resources occupy too much.

  • In the foreground and background mentioned above, the explanations given are: the user clicks on the upper right corner to close, and presses home key to leave Wechat to return to the home page. These situations belong to the situation that the small program enters the background but does not destroy directly. Only when the small program enters the background for a period of time, or when the system resources occupy too much, will it be destroyed, that is to say. The destruction of widgets requires additional conditions, rather than being destroyed directly in the background; when the widget is opened again or the widget is called from the background to the front desk;

2. Life Cycle of Pages

Page life cycle of applets refers to the process of a page in a program from entry to exit or from one page to another.

1. After the registration of the applet is completed, the page is loaded and the onLoad method is triggered. A page can only be called once.

2. The onShow method is triggered after the page is loaded, and the page is displayed. Every time the page is opened, the onShow method is called.

3. When the page is first displayed, the onReady method will be triggered to render the page elements and styles. A page will only be called once.

4. When the applet runs in the background or jumps to other pages, the onHide method is triggered.

5. Trigger the onShow method when the widget enters the foreground or re-enters the page.

6. When the redirect method wx.redirectTo(OBJECT) is used or the current page is closed and returned to the previous page wx.navigateBack(), onUnload is triggered.

3. Life cycle logic of pages A and B under wx.navigateTo jump state

1. Enter page A: A executes onLoad() - > onShow () - > onReady ();

2. A page navigateTo B page: A executes onHide(), B executes onLoad() - > onShow () - > onReady ();

3. Page B returns to page A: B executes onUnload(), A executes onShow().

4. Exit page A: A executes onUnload().

4. Application Life Cycle and Page Life Cycle

1. When the widget is initialized, onLoad will be triggered only once when the page is first loaded.

2. When the applet enters the background, the onHide method of the page is executed before the onHide method is applied.

3. When the small program enters the foreground from the background, the onShow method is applied first and then the onShow method of the page is executed. The application life cycle and the page life cycle are not separate. They work together, cross-use each other, and use the same methods, such as onShow and onHide.

How do widgets introduce other ui components

1. On GitHub Download the program code. After decompression, you can see the following directory:

2. Import the weui.wxss file into the root directory of the applet project.
Add the reference of weui.wxss to the global app.wxss - @import "weui.wxss";

3. Use Reference Documents

<button class="weui-btn" type="primary">Page Master Operation Normal</button>
<view class="weui-cells">
  <view class="weui-cell">
    <view class="weui-cell__bd">
      <text>Title text</text>
    <view class="weui-cell__ft">Explanatory Text</view>

Tags: JSON Windows github REST

Posted on Mon, 02 Sep 2019 20:33:50 -0700 by Il-Belti