首页 前端知识 uni-app中App.vue的onLaunch函数和页面的onLoad函数异步问题的解决方案(Vue2/Vue3)

uni-app中App.vue的onLaunch函数和页面的onLoad函数异步问题的解决方案(Vue2/Vue3)

2024-04-13 23:04:14 前端知识 前端哥 240 353 我要收藏

应用生命周期函数 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>
复制
转载请注明出处或者链接地址:https://www.qianduange.cn//article/4899.html
标签
评论
发布的文章

JQuery中的load()、$

2024-05-10 08:05:15

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!