当前位置:网站首页>Wechat applets - basics takes you to understand the life cycle of applets (I)
Wechat applets - basics takes you to understand the life cycle of applets (I)
2022-06-28 06:43:00 【Oliver Yin】
Hello everyone , This is the sixth article in the applet series , We are still in the basic sharing stage , Although this stage is a little boring , But it is the foundation , Can I use it , But you have to know , Only knowing some basic knowledge can we carry out the development of the project orderly , The addresses of the previous articles are as follows :
1.《 Wechat applet - The basic chapter 》 What is componentization and how to encapsulate applet components
2.《 Wechat applet - The basic chapter 》 Take you to understand the routing system of the applet ( One )
3.《 Wechat applet - The basic chapter 》 Take you to understand the routing system of the applet ( Two )
This article shares some basic knowledge about the life cycle of small programs , Through this article, we can understand the role of the life cycle in the applet , What are the details , And how these lifecycles are used ~
After introducing the foundation, we will actually develop a wechat applet project synchronously and open source , The tentative theme of the project is the original God's data station ~~~
–
Last , Please pay attention to , For collection , Please thumb up , This is a series of articles , Recommended column collection , It must be related to small programs , thank you ~
《 Wechat applet - The basic chapter 》 Take you through the life cycle of an applet ( One )
Preface
There are several chapters from the basic chapter to this chapter , A friend asked me before , How many chapters will there be in the basic chapter , This is the feeling Quite boring , I think about it seriously , You're right , It's all this grammar , I don't know what use it is , It's hard to say whether it can be used in actual work , should Enter the project section earlier ( actual combat ), It is more solid to acquire knowledge in the project ,emmm… with reason , But what I want to say is , These basic articles are really useful , Some basic functions or knowledge points that will definitely be used in the project , Be sure to know ;
This article is mainly about the life cycle of small programs , If you Have studied Vue And so on. MVVM frame , This one in the applet is very easy to understand , It's almost the same , It's just that the method names are different , The usage is almost the same , No difficulty ~ This article does not cover the component lifecycle , The life cycle of components is the next chapter , In this way, you can learn more about the components ;
Read it patiently , You must get something ~
Reading object and difficulty
The difficulty of this article belongs to : primary , fit Developers who are beginning to learn small programs , Through this paper , You can see that What is the role of the lifecycle in an applet , What are the details , And how these lifecycles are used , The general mind map is as follows :
Introduce
Enter in modern times MVVM After the development mode of , All frameworks have a called Life cycle Things that are ,MVVM The development model of has completely subverted MVC That kind of step-by-step rhythm DOM operation ,MVVM it It is a complete method in itself , Or functions , The official saying is From start creation to execution to destruction , This process , We call it the lifecycle of an applet , I personally understand , Simply put, this function Your website will be generated from the beginning to the end , The pages include pages DOM Events on the , Data processing , The interaction of front and back interface data, etc 、 wait .
At certain stages of this function , It allows you to inject some parameters , Method , And the framework will put these methods , Parameters are added to this MVVM In the process of execution , therefore , Some special links have been formed , We can Add the code we want to process in this section , Including some operations for requesting background data , These special links , We call it Life cycle , Let's give you an example
onLaunch function , This function will be executed after the applet is initialized , How do you understand that , The source code of the applet is executed after initialization , Immediately executed onLaunch This function , It's a natural , The code we write in this function will be started together , So , The official also gave a picture that he couldn't understand , As follows :
Look not to understand , No problem , It won't affect our use anyway , Simply put, it describes the trigger timing of each life cycle function during the creation and destruction of the applet ;
Life cycle
Application life cycle
seeing the name of a thing one thinks of its function , These lifecycles are at the applet application level , To put it simply , It's written in app.js In this document , Here's the picture 
Their triggering belongs to the applet application itself , It's just It doesn't matter which page the root user is on , let me put it another way , Users on any page are Can trigger ;
onLaunch
Triggered when the applet is loaded , There is and will only be triggered once , How to put it? , Let's give you an example :
We know that many small programs are Will get the user information of the user , After obtaining the user information, generate an account in your account database and bind the user information , In this way, you can associate the two accounts , All subsequent functions in the applet need to interact based on this account , There's nothing wrong with it , This is a regular content , A lot of times , Our acquisition function is onLaunch This life cycle is realized , If our user information is not onLaunch Implemented in this , Implement... In the life cycle of other pages , such as onShow, The result will be , Every time the page opens, you will get the user information , Think about how bad the user experience will be … Right !
It's easy to use , Look at the code
// app.ts
App<IAppOption>({
globalData: {},
// Execute when applet initialization is complete
onLaunch() {
console.log("onLaunch")
// Jump to log page
wx.navigateTo({
url: './pages/logs/logs'
})
},
})
Combined with the route jump in the previous chapter , So the realization is , When the applet is opened and loaded by the user , It will jump to the log page ;
onShow and onHide
These two are a pair , Let's take a practical example , Suppose we suddenly get a text message while using an applet , Or we used half of it to switch directly to Weibo to see the hot search , So when Applet , Or when wechat is suspended and switched to the background of the mobile phone , Will trigger onHide Life cycle , When we start from something else app When you switch back to wechat and the applet is still open , It will trigger onShow Life cycle , It's that simple , It's also very simple
// app.ts
App<IAppOption>({
globalData: {},
onShow() {
console.log("onShow")
wx.navigateTo({
url: './pages/logs/logs'
})
},
onHide(){
console.log("onHide")
wx.navigateTo({
url: './pages/logs/logs'
})
}
})
This code means When the applet is switched to the background of the mobile phone , The applet jumps back to the log page , When the applet is switched from the background to the foreground for activation , It will also jump to the log page ;
Page lifecycle
If you understand the application lifecycle above , that The page lifecycle should be very easy to understand , It is written in every page , be not in app.js in , Because it is It belongs to page level Of , The example is as follows :
These page level lifecycles are when the page is opened , Leave , Display and so on will be triggered
onLoad
Triggered when the page is loaded , This life cycle is Acceptable query Parameters Of , Let's give you an example :
take loading Page , When many small programs are opened, do they have one loading page , On the other side is the content related to loading smaller programs , On one side is the display advertisement , Kill two birds with one stone , There is a countdown on the ad page , Automatically jump to the home page after the countdown , It is in this process , Can be in onLoad Get the advertisement content you want to display through the interface 
onShow and onHide
and Applied onShow and onHide The functions are the same , The difference lies in , These two lifecycles only belong to the current interface , It will only be triggered when the current interface is displayed or left , Take a scenario example :
User management This page , We usually have two states in this interface : Not logged in and Logged in , When you are not logged in, it shows that you are not logged in UI And function , For example, guide users to register , When logged in, this interface will display the logged in UI, For this scenario , We usually store a user information globally , But every time you open user management , Will go to check , Does this status information exist , For this existence or non existence , Make corresponding logical judgments 
onReady
This function means : Listen when the first rendering of the page is completed , How do you understand that , We know when onShow after , The entire page is rendered , When these renderings are complete, they trigger onReady This life cycle , What's the point , How to put it? , Take an example that is not very appropriate :
When the user logs in successfully , We will identify whether the user is a member , If you are a member , So in For the first time login stay UI There will also be some Special animation effects to show Member effects , But this animation effect is based on DOM On the basis of , If This DOM That is, the node hosting the animation does not exist , Then the animation display will be abnormal , therefore , We have to Make sure that the... That carries the animation DOM There must be , Right , For this kind of , We can put the trigger time of the animation on onReady In this declaration cycle , Because the trigger of this life cycle must be Page rendering complete , And is First rendering ;
in addition , We can also judge from the trigger time , Because we know onShow Is the display page , So according to this statement ,onReady It must be true onShow backstage , We can try it out :
It is completely in line with our conjecture , No problem ~
onUnload
Triggered when the page is unloaded , The official watch is written like this : Life cycle function – Monitor page uninstall , How to understand ? It's simple , Remember when we learned about routing in the last chapter , There are two types of route jumps , Namely :wx.navigateTo and wx.redirectTo, The former can be backed up when jumping to the page , When the latter jumps, the current page will be destroyed , you 're right , This destruction will trigger this function , Do an experiment to verify it
First use wx.navigateTo test
<!--pages/welcome.wxml-->
<view class="btn-group">
<t-button size="small" bind:tap="handleClick"> This is a button </t-button>
</view>
// pages/welcome.ts
Page({
handleClick(user:any){
wx.navigateTo({
url: '../logs/logs'
})
},
/**
* Life cycle function -- Monitor page uninstall
*/
onUnload() {
console.log(" The page triggers a lifecycle function : onUnload")
},
})
The code is roughly as above , Click button , Trigger jump , See if you can print the above ( Please ignore the warning )
Obviously , No printing , Then we change to wx.redirectTo
In line with our expectations , It did print ;
Summary
Finally, let's summarize , Through this paper , We know The life cycle in the applet and the specific meaning and general role of each life cycle , The life cycle is actually in Small program this MVVM The framework is external at certain stages of the runtime api, The official exposes the interface to the developer at these stages , So we developers have the ability to add content to them , It can be divided into several types :
- Application level lifecycle :onLaunch,onShow and onHide;
- Page level lifecycle :onLoad,onShow,onHide,onReady,onUnload;
- Component level lifecycle : We will discuss this in detail in the next section
In the next section we will introduce Life cycle of components , This can be combined with the component development we shared before , Can improve our previous demo Components ~
边栏推荐
- MySQL (I) - Installation
- Install redis on windows and permanently change the password, and integrate redis with the SSM framework
- Deleting MySQL under Linux
- The custom cube UI pop-up dialog supports multiple and multiple types of input boxes
- 微信小程序编译页面空白bug的原因
- Create a gson object that formats the time zone. JSON parsing time formatting zoneddatetime
- Servlet value passing JSP
- 小程序页面设置100%高度还是留白怎么办?
- Rn7302 three-phase electric quantity detection (based on STM32 single chip microcomputer)
- Parsing ng template with let total in NZ Pagination
猜你喜欢

借助nz-pagination中的let-total解析ng-template

AutoCAD C# 多段线自相交检测

Linked list (I) - remove linked list elements

AutoCAD C# 多段线小锐角检测

【网络教程】IPtables官方教程--学习笔记1

推荐10个好用到爆的Jupyter Notebook插件,让你效率飞起

Boost the rising point | yolov5 combined with alpha IOU

VM332 WAService. js:2 Error: _ vm. Changetabs is not a function

Tryout title code

Freeswitch uses origin to dialplan
随机推荐
FPGA - 7 Series FPGA selectio -09- io of advanced logic resources_ FIFO
Alert pop-up processing in Web Automation
Idea generates entity classes from database tables
Note that JPA uses a custom VO to receive jpql query results
4~20ma input /0~5v output i/v conversion circuit
MySQL (II) - basic operation
Promotion intégrale et ordre des octets de fin de taille
CAD secondary development +nettopologysuite+pgis reference multi version DLL
Puge -- understanding of getordefault() method
AutoCAD C# 多段線小銳角檢測
FPM tool installation
饿久了,大脑会进入“省电模式”!感官被削弱,还看不清东西丨爱丁堡大学...
Linked list (II) - Design linked list
三极管驱动无刷电机
Install and manage multiple versions of PHP under mac
Linux Mysql 实现root用户不用密码登录
ThreadLocal
Iphone6plus enters the list of antique products netizen: I'm still using it
UPC -- expression evaluation
Puge -- singleton mode