Table of Contents
1. Life cycle
2. Life cycle function
Home WeChat Applet Mini Program Development Let's talk about the life cycle (function) in WeChat applet

Let's talk about the life cycle (function) in WeChat applet

Nov 01, 2021 am 10:24 AM
Applets WeChat life cycle

This article will take you to take a look at the life cycle in the WeChat applet, what life cycle functions are there, and talk about its triggering time and what it does. I hope it will be helpful to everyone!

Let's talk about the life cycle (function) in WeChat applet

1. Life cycle

1. What is life cycle?

Life Cycle(Life Cycle) refers to the entire stage of an object from creation-> running-> destruction, emphasizing a time period

2. The life cycle of the mini program

  • Startup of the mini program represents the life cycle Start
  • Close of the applet, indicating the end of the life cycle
  • The process of running the applet in the middle is the life of the applet Cycle

3. Mini program life cycle classification

  • Application life cycle Specifically refers to the process of mini program starting --> running --> destruction

  • Page life cycle Specifically refers to the loading--> rendering--> destruction process of each page in the mini program

  • Note: The life cycle range of the page is small , the life cycle range of the application is larger

Lets talk about the life cycle (function) in WeChat applet

2. Life cycle function

1. What is a life cycle function?

  • The built-in functions provided by the mini program framework will be automatically executed in sequence along with the life cycle

  • Life cycle The role of the function:

    • Allows programmers to perform certain operations at specific life cycle time points
    • For example, when the page is just loaded, in the life cycle function Automatically initiate a data request to obtain the data of the current page
  • Note: The life cycle emphasizes the time period, and the life cycle function emphasizes the time point.

2. Application life cycle function

  • app.js is the entry file for mini program execution. The App() function must be called in app.js and can only be called once. Among them, the App() function is used to register and execute the applet.

  • App(Object) function receives an Object Parameters, you can specify the life cycle function of the applet through this Object parameter

  • Code in app.js

The code is as follows (example):

App({

  /**
   * 当小程序初始化完成时,会触发 onLaunch(全局只触发一次)
   */
  onLaunch: function () { },

  /**
   * 当小程序启动,或从后台进入前台显示,会触发 onShow
   */
  onShow: function (options) { },

  /**
   * 当小程序从前台进入后台,会触发 onHide
   */
  onHide: function () { },

  /**
   * 当小程序发生脚本错误,或者 api 调用失败时,会触发 onError 并带上错误信息
   */
  onError: function (msg) { }
})
Copy after login

3. Page life cycle

  • Each mini program page must have its own .js file, and must call the Page() function, otherwise an error will be reported. Among them, the Page() function is used to register the mini program page.

  • Page(Object) function receives an Object parameter. , you can specify the life cycle function of the page through this Object parameter

  • page.js

The code is as follows (example):

//index.js
//获取应用实例
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: { },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) { },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () { },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () { },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () { }
})
Copy after login

4. The entire life cycle of components

What are the life cycles of components? When are they different?

Life cycleParametersDescription
createdNoneExecuted when the component instance is just created
attachedNoneExecuted when the component instance enters the page node tree
readyNoneExecuted after the component is laid out in the view layer
movedNone Executed when the component instance is moved to another location in the node tree
detachedNoneExecuted when the component instance is removed from the page node tree
errorObject ErrorEvery Executed when a component method throws an error

5. 组件主要的生命周期函数

data在哪个生命周期中初始化完毕?

组件的生命周期,指的是组件自身的一些函数,这些函数在特殊的时间点或遇到一些特殊的框架事件时被自动触发。

最重要的生命周期是 created, attached, detached ,包含一个组件实例生命流程的最主要时间点。

  • 组件实例刚刚被创建好时, created 生命周期被触发

    • 此时还不能调用 setData
    • 通常情况下,这个生命周期只应该用于给组件 this 添加一些自定义属性字段
  • 在组件完全初始化完毕、进入页面节点树后, attached 生命周期被触发

    • this.data 已被初始化完毕
    • 这个生命周期很有用,绝大多数初始化工作可以在这个时机进行
  • 在组件离开页面节点树后, detached 生命周期被触发

    • 退出一个页面时,会触发页面内每个自定义组件的detached 生命周期被触发
    • 如果组件还在页面节点树中,则 detached 会被触发。
    • 此时适合做一些清理性质的工作

6. lifetimes 节点

同时以两种方式声明生命周期函数,会执行哪个?

生命周期方法可以直接定义在 Component 构造器的第一级参数中,组件的的生命周期也可以在 lifetimes 字段内进行声明(这是推荐的方式,其优先级最高)

lifetimes: {
  attached () {
    console.log('在组件实例进入页面节点树')
  },
  detached () {
    console.log('在组件实例被从页面节点树移除')
  }
},

attached () {
  console.log('~~~~~在组件实例进入页面节点树')
},
detached () {
  console.log('~~~~~在组件实例被从页面节点树移除')
},

/**
 * 组件的初始数据
 */
data: {
  // rgb 的颜色值对象
  _rgb: {
    r: 0,
    g: 0,
    b: 0
  },
  // 根据 rgb 对象的三个属性,动态计算 fullColor 的值
  fullColor: '0, 0, 0'
}
Copy after login

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of Let's talk about the life cycle (function) in WeChat applet. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

deepseek image generation tutorial deepseek image generation tutorial Feb 19, 2025 pm 04:15 PM

DeepSeek: A powerful AI image generation tool! DeepSeek itself is not an image generation tool, but its powerful core technology provides underlying support for many AI painting tools. Want to know how to use DeepSeek to generate images indirectly? Please continue reading! Generate images with DeepSeek-based AI tools: The following steps will guide you to use these tools: Launch the AI ​​Painting Tool: Search and open a DeepSeek-based AI Painting Tool (for example, search "Simple AI"). Select the drawing mode: select "AI Drawing" or similar function, and select the image type according to your needs, such as "Anime Avatar", "Landscape"

gateio Chinese official website gate.io trading platform website gateio Chinese official website gate.io trading platform website Feb 21, 2025 pm 03:06 PM

Gate.io, a leading cryptocurrency trading platform founded in 2013, provides Chinese users with a complete official Chinese website. The website provides a wide range of services, including spot trading, futures trading and lending, and provides special features such as Chinese interface, rich resources and community support.

List of handling fees for okx trading platform List of handling fees for okx trading platform Feb 15, 2025 pm 03:09 PM

The OKX trading platform offers a variety of rates, including transaction fees, withdrawal fees and financing fees. For spot transactions, transaction fees vary according to transaction volume and VIP level, and adopt the "market maker model", that is, the market charges a lower handling fee for each transaction. In addition, OKX also offers a variety of futures contracts, including currency standard contracts, USDT contracts and delivery contracts, and the fee structure of each contract is also different.

gateio exchange app old version gateio exchange app old version download channel gateio exchange app old version gateio exchange app old version download channel Mar 04, 2025 pm 11:36 PM

Gateio Exchange app download channels for old versions, covering official, third-party application markets, forum communities and other channels. It also provides download precautions to help you easily obtain old versions and solve the problems of discomfort in using new versions or device compatibility.

Ouyi Exchange app domestic download tutorial Ouyi Exchange app domestic download tutorial Mar 21, 2025 pm 05:42 PM

This article provides a detailed guide to safe download of Ouyi OKX App in China. Due to restrictions on domestic app stores, users are advised to download the App through the official website of Ouyi OKX, or use the QR code provided by the official website to scan and download. During the download process, be sure to verify the official website address, check the application permissions, perform a security scan after installation, and enable two-factor verification. During use, please abide by local laws and regulations, use a safe network environment, protect account security, be vigilant against fraud, and invest rationally. This article is for reference only and does not constitute investment advice. Digital asset transactions are at your own risk.

Sesame Open Door Login Registration Entrance gate.io Exchange Registration Official Website Entrance Sesame Open Door Login Registration Entrance gate.io Exchange Registration Official Website Entrance Mar 04, 2025 pm 04:51 PM

Gate.io (Sesame Open Door) is the world's leading cryptocurrency trading platform. This article provides a complete tutorial on spot trading of Gate.io. The tutorial covers steps such as account registration and login, KYC certification, fiat currency and digital currency recharge, trading pair selection, limit/market transaction orders, and orders and transaction records viewing, helping you quickly get started on the Gate.io platform for cryptocurrency trading. Whether a beginner or a veteran, you can benefit from this tutorial and easily master the Gate.io trading skills.

How to copy Xiaohongshu copywriting. Graphical tutorial on how to copy Xiaohongshu copywriting. How to copy Xiaohongshu copywriting. Graphical tutorial on how to copy Xiaohongshu copywriting. Jan 16, 2025 pm 04:03 PM

Learn to easily copy Xiaohongshu copywriting! This tutorial teaches you step by step how to quickly copy Xiaohongshu video copy, saying goodbye to tedious steps. Open the Xiaohongshu APP, find the video you like, and click on the [Copywriting] area below the video. Long press the copy text and select the [Extract Text] function from the pop-up options. The system will automatically extract the text, click the [Copy] button in the lower left corner. Open WeChat or other applications, such as Moments, long press the input box, and select [Paste]. Click Send to complete the copy. It's that simple!

The difference between H5 and mini-programs and APPs The difference between H5 and mini-programs and APPs Apr 06, 2025 am 10:42 AM

H5. The main difference between mini programs and APP is: technical architecture: H5 is based on web technology, and mini programs and APP are independent applications. Experience and functions: H5 is light and easy to use, with limited functions; mini programs are lightweight and have good interactiveness; APPs are powerful and have smooth experience. Compatibility: H5 is cross-platform compatible, applets and APPs are restricted by the platform. Development cost: H5 has low development cost, medium mini programs, and highest APP. Applicable scenarios: H5 is suitable for information display, applets are suitable for lightweight applications, and APPs are suitable for complex functions.

See all articles