Detailed explanation of WeChat applet development

Detailed explanation of WeChat applet development

foreword

In this article, I will lead you to deeply explore the principles and technologies of WeChat mini-program development, including the mini-program framework, components, events, etc. Let everyone have a better understanding of the development process and principles of small programs.

What are WeChat Mini Programs?

A WeChat Mini Program is an application that can run in WeChat. It uses the development framework and tools provided by WeChat and can be used directly without downloading and installing. WeChat applets adopt a web-like development method, and developers can use front-end technologies such as HTML, CSS, and JavaScript for development.

Compared with traditional web applications, WeChat Mini Programs have the following characteristics:

  • No need to download and install, use it directly in WeChat
  • Part of the system API can be accessed to achieve more powerful functions
  • Through the development framework and tools provided by WeChat, it is convenient to develop, test and release

Mini Program Framework

The Mini Program framework is the core of WeChat Mini Program development. It is responsible for the entire life cycle management, page rendering, data binding, event handling and other aspects of the Mini Program. The Mini Program framework is provided by the WeChat team. Developers can quickly build Mini Programs by using the Mini Program Framework.

How the Mini Program Framework Works

The working principle of the applet framework can be briefly summarized as the following steps:

  1. Parsing the applet code: The applet framework will parse the applet code written by the developer and convert the code into executable JavaScript code.
  2. Initialize the applet: The applet framework will initialize the applet, including the registration page, components, etc., and start the life cycle of the applet.
  3. Page rendering: When the applet is started, the applet framework will render the structure, style and data of the page to the screen according to the page definition.
  4. Data binding: The applet framework supports data binding. When the data changes, the applet framework will automatically update the corresponding page view.
  5. Event processing: The applet framework will monitor user interaction events, such as clicks, slides, etc., and trigger corresponding event processing functions according to event types.

Components of the applet framework

The applet framework consists of four layers: frame layer, stimulate layer, view layer, and logic layer:

  1. Frame layer: The applet runs the container and provides a running environment.
  2. The stimulate layer: defines the life cycle and events of the applet. Scripts written by developers will be managed and invoked by the stimulate layer.
  3. View layer: composed of WXML and WXSS, used to define the applet interface and style.
  4. Logic layer: composed of JavaScript, used to define the interaction logic and data processing of the applet.
    A standard WeChat applet generally consists of the following file structure

├── app.js // applet logic file
├── app.json // applet global configuration
├── app.wxss // applet global style sheet
├── pages // page file directory
│ ├── index
│ │ ├── index.js // page logic
│ │ ├── index.json // page configuration
│ │ ├── index.wxml // page structure
│ │ └── index.wxss // page style sheet
│ └── …
├── components // component file directory
│ └── …
├── images // image resource directory
├── utils // utility function directory
└── project.config.json // project configuration file
app.js: applet logic file, used to handle logic and events at the applet application level.
app.json: The global configuration file of the applet, which is used to set the name, version and other information of the applet.
app.wxss: Applet global style sheet, set the global general style.
pages: stores the page files of the applet, and each folder represents a page, which contains four files:
index.js: page logic file
index.wxml: page structure file
index.json: page configuration file
index.wxss: page style sheet
components: stores the custom components of the applet, which can be referenced in the page.
images: image resource directory, where the page images in the applet are stored.
utils: Tool function directory, used to store non-page or component-related functions.
project.config.json: Applet project configuration file, used to configure project information, appid, packOptions, etc.
The three directory hierarchies of pages, components, and utils are flattened. Components under components can be referenced in the page, and functions defined in utils can be used in components and pages.

The life cycle of the applet framework

The applet framework has its own life cycle, which can be divided into two parts: the global life cycle and the page life cycle.

global lifetime

The global life cycle refers to the life cycle of the entire applet, which includes the following stages:

App() function: The applet is initialized and executed only once globally. Used for global initialization, registering events, etc.

  1. onLaunch: Triggered when the applet starts, used to initialize the global data of the applet.
  2. onShow: Triggered when the applet is displayed in the foreground, used to process the logic when entering the applet.
  3. onHide: Triggered when the applet is switched from the foreground to the background, used to handle the logic when the applet is running in the background.
  4. onError: Triggered when an error occurs in the applet, used to handle the reporting and processing of the error information of the applet.

page life cycle

The page life cycle refers to the life cycle of each page in the applet, which includes the following stages:

Page() function: Used to define page configuration, event processing logic, etc. Every page needs to declare this function.

  1. onLoad: Triggered when the page is loaded, used to process the logic of page initialization data.
  2. onShow: Triggered when the page is displayed, used to process the logic when the page is displayed.
  3. onReady: Triggered when the page rendering is completed, used to process the logic after the page rendering is completed.
  4. onHide: Triggered when the page is switched from the foreground to the background, used to handle the logic when the page is running in the background.
  5. onUnload: Triggered when the page is unloaded, used to handle the logic when the page is unloaded.

applet component

Applet components are reusable parts in applets, including common UI components such as buttons, input boxes, and lists, as well as custom components. Small program components can improve development efficiency, reduce code redundancy, and are also conducive to code maintenance and upgrades. It has the following main features:

  1. Componentization: Components with a certain complexity can be built to realize the decoupling of UI and functions.
  2. Reusable: Components can be used in multiple pages, avoiding repeated development.
  3. Isolation scope: Components have their own scope, and styles and logic will not affect external pages.
  4. Complete lifecycle: Components have a complete lifecycle that allows precise control over their behavior.

How to define components:

Create a component folder in the components directory, and create four files of json, js, wxml, and wxss in the same directory. The file name is the same as the folder name.
components/
├── comp-a
│ ├── comp-a.js // Component logic
│ ├── comp-a.json // Component configuration
│ ├── comp-a.wxml // Component structure
│ └─ ─ comp-a.wxss // component style sheet
└── …

Relationship between components:

Components can be used in the pages page, and the pages page can also use other components nested in the component. The level of components is not limited, and complex component trees can be built.
Use components: Declare the used components in the json file of the page and reference them in wxml.

// page.json 
{
    
    
  "usingComponents": {
    
    
    "comp-a": "/components/comp-a/comp-a" 
  }
}
<!-- page.wxml -->
<comp-a /> 

Component style isolation:

By default, the style of the component only acts on the inside of the component and will not affect the outside world. But you can use external styles in the component wxss file or set the CSS selector of the component's root element to act externally.

/* comp-a.wxss */
.root {
    
     /* 组件根元素选择器 */ 
  color: red; 
}

/* page.wxss */
.root {
    
    
  font-size: 40rpx;
} 

Component data monitoring:

The page can change the data passed to the component through setData, and the component responds to data changes by listening to properties.

js
// page.js
this.setData({
    
    
  compData: 'data changed' 
})

// comp.js
Component({
    
    
  properties: {
    
    
    compData: String 
  },
  observers: {
    
    
    'compData': function(newVal) {
    
    
      console.log(newVal) // data changed 
    } 
  }  
}) 

Component events:

Components can trigger their own custom events, and can also receive events triggered by the page.
Component trigger event: trigger the event through this.triggerEvent(eventName, data), and the page listens through the event proxy.

// comp.js
Component({
    
    
  methods: {
    
    
    clickHandle() {
    
    
      this.triggerEvent('myEvent', {
    
    name: 'John'})
    } 
  } 
})

// page.js 
Page({
    
    
  onMyEvent(ev) {
    
    
    console.log(ev.detail.name) // John
  } 
}) 

Components receive events:

Declare the accepted event name in the component's json file, and define the processing function in methods.

// comp.json
{
    
    
  "events": {
    
     
    "myEvent": "onMyEvent" 
  } 
}
// comp.js
Component({
    
    
  methods: {
    
    
    onMyEvent(ev) {
    
    
      console.log(ev)
    }
  }  
})

Component communication:

There are mainly the following ways for applet components to communicate:

1. Event binding and triggering: Through event binding and triggering, the interaction between components is realized. For example, an event is defined in the parent component, the event is triggered in the child component, and the child component transmits data to the parent component through the event processing function.

Parent component sample code:

//wxml文件
<child-component bindmyevent="onMyEvent"></child-component>
//js文件
Page({
    
    
  data: {
    
    
    message: ''
  },
  onMyEvent: function(event) {
    
    
    this.setData({
    
    
      message: event.detail.message
    })
  }
})

Subcomponent sample code:

Component({
    
    
  methods: {
    
    
    sendMsg: function() {
    
    
      this.triggerEvent('myevent', {
    
    message: 'Hello World'})
    }
  }
})

2. Attribute value passing: By passing attribute values ​​to child components, the parent component can transfer data to the child components. For example, define a property value in the parent component, and the child component obtains the value by using the properties attribute.

parent component

//wxml文件
<child-component message="{
     
     {message}}"></child-component>
//js文件
Page({
    
    
  data: {
    
    
    message: 'Hello World'
  }
})

Subassembly

Component({
    
    
  properties: {
    
    
    message: {
    
    
      type: String,
      value: ''
    }
  }
})

3.Page.setData(): The Page object provides the setData() method, which can realize data transfer between components. For example, in a Page page, data can be passed to subcomponents through the setData() method.

parent component:

//wxml文件
<child-component></child-component>
//js文件
Page({
    
    
  data: {
    
    
    message: ''
  },
  onMyEvent: function(event) {
    
    
    this.setData({
    
    
      message: event.detail.message
    })
  }
})

Subassembly

Component({
    
    
  methods: {
    
    
    sendMsg: function() {
    
    
      let pages = getCurrentPages()
      let currentPage = pages[pages.length - 1]
      currentPage.setData({
    
    
        message: 'Hello World'
      })
    }
  }
})

4. Event bus: Using the event bus can realize data transfer across components. The event bus is an event publish/subscribe pattern, which implements communication between components by subscribing to events and publishing events.

sample code

//event.js文件
const eventBus = {
    
    
  events: {
    
    },
  on: function(eventName, callback) {
    
    
    if (!this.events[eventName]) {
    
    
      this.events[eventName] = []
    }
    this.events[eventName].push(callback)
  },
  off: function(eventName, callback) {
    
    
    let callbacks = this.events[eventName]
    if (callbacks) {
    
    
      this.events[eventName] = callbacks.filter((item) => item !== callback)
    }
  },
  emit: function(eventName, data) {
    
    
    let callbacks = this.events[eventName]
    if (callbacks) {
    
    
      callbacks.forEach((callback) => callback(data))
    }
  }
}

module.exports = eventBus

parent component

//wxml文件
<child-component></child-component>
//js文件
const eventBus = require('event.js')
Page({
    
    
  data: {
    
    
    message: ''
  },
  onLoad: function() {
    
    
    eventBus.on('myevent', (data) => {
    
    
      this.setData({
    
    
        message: data.message
      })
    })
  }
})

Subassembly

const eventBus = require('event.js')
Component({
    
    
  methods: {
    
    
    sendMsg: function() {
    
    
      eventBus.emit('myevent', {
    
    message: 'Hello World'})
    }
  }
})

5. getApp(): Obtain the applet instance through the getApp() method to realize cross-page data transfer. Data sharing between components can be realized by defining global variables or methods in the applet instance.

//app.js文件
App({
    
    
  globalData: {
    
    
    message: ''
  }
})

parent component

//wxml文件
<child-component></child-component>
//js文件
const app = getApp()
Page({
    
    
  data: {
    
    
    message: ''
  },
  onLoad: function() {
    
    
    this.setData({
    
    
      message: app.globalData.message
    })
  }
})

Subassembly

const app = getApp()
Component({
    
    
  methods: {
    
    
    sendMsg: function() {
    
    
      app.globalData.message = 'Hello World'
    }
  }
})

Applet event

Mini-program events refer to events triggered when the user interacts with the mini-program, such as clicks, slides, and so on. The applet framework can monitor these events and execute corresponding event processing functions. Applet events include:

  • touchstart: Triggered when the finger touch starts.
  • touchmove: Triggered when the finger touches and moves.
  • touchend: Triggered when the finger touch ends.
  • tap: Triggered when the finger taps.
  • longpress: Triggered when the finger is long pressed.
  • scrolltoupper: Triggered when scrolling to the top.
  • scrolltolower: Triggered when scrolling to the bottom.

Applet events can be bound to components or pages. The method of binding the event is as follows:

  1. In the wxml file of the component or page, add an event binding attribute for the component or element that needs to bind the event, such as bindtap, bindlongpress, etc.
  2. In the js file of the component or page, define the corresponding event handling function, and the function name needs to be the same as the suffix of the bound property.
  3. In the event processing function, the event object can be used to obtain relevant information about the trigger event, such as the location where the event is triggered, the component that triggers the event, and so on.

code example

<!-- wxml -->
<view>
  <button bindtap="handleTap">点击按钮</button>
</view>
// js
Page({
    
    
  handleTap: function() {
    
    
    console.log('按钮被点击了')
  }
})

Mini Program API

Mini Program APIs are some functional interfaces provided by Mini Programs. Developers can implement various functions by calling these interfaces. Mini Program APIs can be divided into basic APIs and extended APIs.

Basic API

Mini Program Basic API includes some common functional interfaces, such as data storage, network request, audio and video playback, etc. These APIs can meet the needs of most applets.

The following are some commonly used basic APIs:

  • wx.request: Initiate a network request.
  • wx.showToast: Display the message prompt box.
  • wx.showLoading: Display the loading prompt box.
  • wx.hideLoading: Hide the loading prompt box.
  • wx.setStorageSync: Synchronize storage data.
  • wx.getStorageSync: Get stored data synchronously.
  • wx.playBackgroundAudio: Play background music.
    insert image description here

extension API

The Mini Program Extension API is based on the basic API and provides some more advanced functional interfaces, such as image recognition, speech recognition, etc. These APIs need to be activated in the background of the mini program management, and developers need to have certain technical capabilities to use them.

The following are some commonly used extension APIs:

  • wx.createCameraContext: Create a camera context object.
  • wx.createCanvasContext: Create a canvas context object.
  • wx.createInnerAudioContext: Create an inner audio context object.
  • wx.createVideoContext: Create a video context object.
  • wx.getBackgroundAudioManager: Get the globally unique background audio manager.

Mini Program Development Tool

Mini program development tool is an integrated development environment (IDE) for mini program development, which can help developers complete code writing, debugging, packaging and other tasks.

The applet development tool includes the following functions:

  • Code editor: supports auto-completion, syntax highlighting, code folding and other functions.
  • Debugging tool: It can be debugged in various ways such as real machine debugging, emulator debugging, and web page debugging.
  • Management background: It can manage the release version of the applet, data analysis, operation and promotion, etc.
  • Packaging tool: You can package the applet into a release version, and support custom version number, description and other information.

The method of using the applet development tool is relatively simple. After downloading and installing, create a applet project in the tool to start development.

Small program optimization skills

During the development of applets, in order to improve the performance and user experience of applets, it is often necessary to use some optimization techniques such as:

  1. Reduce network requests: The network requests of applets are slow, so it is necessary to reduce the number of network requests as much as possible, which can be achieved by data caching and merging requests.
  2. Reduce the number of page renderings: The page rendering of applets is slow, so it is necessary to reduce the number of page renderings as much as possible, which can be achieved by template rendering and data lazy loading.
  3. Avoid using global variables: Global variables in applets will take up more memory, so you need to avoid using global variables, which can be achieved through data transfer and componentization.
  4. Avoid frequent triggering of setData: The setData operation of the applet will cause the page to redraw, so it is necessary to avoid frequent triggering of setData, which can be achieved by throttling and anti-shake.
  5. Use the Mini Program API: The Mini Program provides some performance-optimizing APIs, such as wx.createIntersectionObserver, wx.createSelectorQuery, etc., which can help developers optimize the performance of the Mini Program.

epilogue

WeChat Native Mini Program is a fast-developing, lightweight application that is suitable for application development in various scenarios. This article introduces the development of WeChat applets from various aspects, hoping to help everyone

Guess you like

Origin blog.csdn.net/2303_76218115/article/details/130322118