Don't stop at vue, explore the life cycle of uni-app



What is the life cycle?

First, in Vue each instance goes through a series of initialization steps.

When it is created, from setting the data, to compiling the template, to mounting the instance to the DOM, and finally updating the DOM when the data changes. This process is called the life cycle of Vue instances, and as they go through this process of creating and updating the DOM, there are some functions that run in it by default. It is inside them that Vue components are created and exist, and these functions are called lifecycle hooks.

The concept of life cycle in English is not only applied to front-end technologies such as vue , react, etc., of course, it also exists in uni-app, just like a person's life, from birth to release, corresponding to the code, an object This process from create, run, and destroy is called the life cycle.



Environmental preparation

We use the official HBuilderX for development

We create a new project
image.png

Select uni-app, we choose the default template to create it
Screenshot 2022-04-02 20.54.54.png



uni-app life cycle

application life cycle

App.vueThe Lifecycle Hooks of the application are defined in it : the application life cycle hook function , we simply say the application life cycle .

The application life cycle is used to control the global life cycle of the entire application, and monitor the initialization, startup, and exit status of the application.

uni-appThe following application lifecycles are supported:

  • onLaunch : Triggered when initialization is complete (only triggered once globally). Usually used to initialize pre-data, such as obtaining user information.

  • onShow : Start or go from the background to the foreground display. For example, the app was placed in the background, and now it is entered from the background. It can be used when the data needs to be refreshed when the page is opened for the second time.

  • onHide : Enter the background from the foreground. For example, when using the app to return to the desktop, the app will be placed in the background and it will be triggered. Can be used to clear cache or protect privacy.

    The above are more commonly used, but the following are also important

  • onError : Triggered when an error is reported.

  • onUniNViewMessage : Monitor the data sent by the nvuepage .

  • onUnhandledRejection : Listener function for unhandled Promiserejection events.

  • onPageNotFound : The listener function when the page does not exist.

  • onThemeChange : Listen for system theme changes. If you want to adapt a dark theme for your application, you can listen for system theme changes in this function and switch the corresponding program theme.

It should be noted here that it is onLaunchonly triggeredonLaunch hooks once when the global initialization is completed; the data of Vue has not been loaded when it is triggered for the first time, and in the code, it is , and this , did not load.uni-apponShowmounteddataDOM

Because here is the application life cycle so we write content App.vueinside . (This is just an example and does not represent an actual application scenario)

<script>
    export default {
      
      
        data() {
      
      
            return {
      
      
            latest_data_timer: 0,
            stop_time: 0,
            };
        },
        methods: {
      
      
            // 假设这是某些信息的 API
            getNowUserInfo() {
      
      
                return {
      
      
                    user: "我想养只猫",
                    webSite: "uiuing.com",
                    token: "123abclkd",
                };
            },
            // 假设通过这个方法一直在加载数据
            latestData() {
      
      
            this.latest_data_timer = setInterval(() => {
      
      
                    console.log("Now user info:", this.getNowUserInfo());
                }, 2000);
            },
        },
        onLaunch: function () {
      
      
            console.log("欢迎您的使用,我只加载一次~");
        },
        onShow: function () {
      
      
            console.log("开始加载数据,注意此时vue数据没加载完");

            // 告知数据暂停了多久
            if (this.stop_time) {
      
      
            let load_interval_time = new Date().getTime() - this.stop_time;
            console.log("数据暂停了:", load_interval_time / 1000, "秒");
            }

            // 开始加载
            this.latestData();
        },
        onHide: function () {
      
      
            console.log("检测到App在后台,暂停内容加载");

            // 记录暂停时的时间戳
            this.stop_time = new Date().getTime();

            // 暂停加载
            clearInterval(this.latest_data_timer);
        },
    };
</script>

image.png




page life cycle

Page life cycle That is: the life cycle of a single page, monitoring the status of page loading, page display, page rendering, hiding, and unloading.

Page life cycle Commonly used onLoad: executed at the first load, only executed once, generally used to click on the previous level to enter the next level, and used when parameters need to be passed. onShow: Executed when the page is first loaded, and also fired when returning from a secondary page.

uni-appThe commonly used page life cycle hook functions are as follows:

  • onLoad : Monitor page loading, its parameter is the data passed by the previous page, and the parameter type is Object.

  • onShow : Monitor the display of the page, which is triggered every time the page appears on the screen, including returning from the lower-level page to reveal the current page.

  • onReady : Monitors the completion of the initial rendering of the page.

  • onHide : Listen for page hiding.

  • onUnload : Listen for page unloading.

  • onPullDownRefresh : Listen to the user's pull-down action, generally used for pull-down refresh.

Because here is the page life cycle , so we create a page /pages/Home/index.vueto write content here.

<template>
  <view></view>
</template>

<script>
	export default {
      
      
		onReady() {
      
      
			console.log("页面初次渲染完成");
		},
		onLoad() {
      
      
			console.log("页面加载动作");
		},
		onShow() {
      
      
			console.log("页面显示动作");
		},
		onHide() {
      
      
			console.log("页面隐藏动作");
		},
		onUnload() {
      
      
			console.log("页面关闭动作");
		},
		onPageScroll() {
      
      
			console.log("页面滚动动作");
		},
	};
</script>

<style></style>

image.png


For onPullDownRefresh need to be used like this:

(This is just an example and does not represent an actual application scenario)

It needs pages.jsonto be enabled in the style option in enablePullDownRefresh.

  • uni.startPullDownRefresh() : Start the pull-down refresh of the current page.
  • uni.stopPullDownRefresh() : Stop the pull-down refresh of the current page.
"pages": [
        {
    
    
            "style": {
    
    
                "enablePullDownRefresh": true // 添加
            }
        }
    ],
onShow() {
    
    
    // 开始下拉
    uni.startPullDownRefresh();
},
onPullDownRefresh() {
    
    
    // 4秒后关闭下拉
    setTimeout(function () {
    
    
            uni.stopPullDownRefresh();
    }, 4000);
}

image.png


There is also a component life cycle, which is the life cycle of Vue, which will not be repeated here.



Guess you like

Origin blog.csdn.net/qq_41103843/article/details/123936227