The sequence of execution of onLaunch and onload in uniapp

The sequence of execution of onLaunch and onload in uniapp

onLaunch and onload are APP life cycle and page life cycle respectively. In theory, onLaunch should be executed first and then page life cycle onLoad should be executed. However, this is not the case in practice. When onlaunch is executed, the onLoad life cycle is also executed. In actual development, it is often necessary to execute onlaunch first and then onLoad, so the current method can be used to solve the problem.

1. Add the following code to main.js?

The code is as follows (example)

// 让页面的 onLoad 在 onLaunch 之后执行
Vue.prototype.$onLaunched = new Promise(resolve => {
    
    
    Vue.prototype.$isResolve = resolve
})

2. Add the code this.$isResolve() in onLaunch of App.vue;

The code is as follows (example):

//app.vue生命周期中,onlaunch执行时,执行this.$isResolve()
onLaunch () {
    
    
	//发送请求
    uni.request({
    
    
        success: loginRes => {
    
            
            // 业务逻辑
            // ...
            // 当执行完业务逻辑,需要同步onload时,调用一下
            this.$isResolve()            
        }
    })
}

3. Add the code await this.$onLaunched in the page onLoad;

The code is as follows (example):

//onLoad 生命周期函数前,加async/await,用此方法同步执行顺序
	async onLoad() {
    
    
		//async/await,当执行完APP生命周期中的onlaunch,再执行页面中的业务逻辑
		await this.$onLaunched;
		
		//执行页面中的业务逻辑
		//...
	},

personal understanding

1. First set a promise instance for the onLaunch method, and then execute the global mounting method after the execution is successful, indicating that the current execution has been completed.
2. Use async/await to execute the code synchronously on the page, so that onLaunch is executed after onLoad

Non-original, reproduced from the following link (thanks for sharing)

Link: Use Promise in uni-app to implement onLaunch asynchronous callback and then execute onLoad .

Guess you like

Origin blog.csdn.net/weixin_46746389/article/details/119318273