应用生命周期函数 onLaunch 和页面生命周期函数 onLoad 存在同时执行的问题,而在实际开发中往往需要先执行 onLaunch 再执行 onLoad,为了让页面的 onLoad 在 onLaunch 之后执行,可以使用以下解决方案:
Vue2 中的解决方案
1 修改 main.js
Vue.prototype.$onLaunched = new Promise(resolve => { Vue.prototype.$isResolve = resolve })
复制
2 修改 App.vue
在 App.vue 的 onLaunch 所有业务逻辑执行完毕后增加代码 this.$isResolve()
onLaunch: function() { this.getConfig().then(res => { // 业务逻辑执行完毕 this.$isResolve() }) },
复制
或者
async onLaunch: function() { await this.getConfig() // 业务逻辑执行完毕 this.$isResolve() },
复制
3 修改页面
在页面的 onLoad 中增加代码 await this.$onLaunched,注意onload要添加async
async onLoad(option) { //等待倒计时 await this.$onLaunched; // 后续业务逻辑 },
复制
Vue3 的解决方案
// main.js import App from './App' import { createSSRApp } from 'vue' export function createApp() { const app = createSSRApp(App) app.config.globalProperties.$onLaunched = new Promise(resolve => { app.config.globalProperties.$isResolve = resolve }) return { app } }
复制
<script setup> // App.vue import { onLaunch } from '@dcloudio/uni-app' import {getCurrentInstance} from 'vue' const { proxy } = getCurrentInstance(); const {$isResolve} = proxy onLaunch(() => { setTimeout(() => { $isResolve() }, 3000) }) </script>
复制
<script setup> // page 页面中 import {getCurrentInstance} from 'vue' const {proxy} = getCurrentInstance(); const {$onLaunched} = proxy import {onLoad} from '@dcloudio/uni-app' onLoad(async ()=>{ // 等待倒计时 await $onLaunched; // 后续业务逻辑 }) </script>
复制