uniapp 应用启动onLaunch方法,改为同步,执行后再执行页面加载onLoad方法 |
您所在的位置:网站首页 › vue等待接口返回再执行 › uniapp 应用启动onLaunch方法,改为同步,执行后再执行页面加载onLoad方法 |
问题描述
app.vue里的onLaunch中如果有异步方法,返回结果可能会在页面的 onLoad 之后,为了让页面的 onLoad 在 onLaunch 之后执行,使用以下解决方案 方案一 1、main.js添加如下代码 Vue.prototype.$onLaunched = new Promise(resolve => { Vue.prototype.$isResolve = resolve }) 2、应用启动时,设置需要等待的逻辑 在 App.vue 的 onLaunch 中增加代码 this.$isResolve()这个方法必须在你的业务如ajax执行完毕后再执行 另外注意要用箭头函数,否则this不好使 onLaunch: function() { console.log('App Launch'); console.log('倒计时10秒'); setTimeout(() => { console.log('倒计时结束'); this.$isResolve() },5000); }, 3、在页面 onLoad 中增加等待代码 await this.$onLaunched注意onload要添加async,否则编译不过去 async onLoad(option) { //等待倒计时 await this.$onLaunched; console.log("等待倒计时结束后打印"); // 后续业务逻辑 }, 4、在chrome运行截图如下,小程序等支持ES6环境才行uniapp同步方法实例代码-Javascript文档类资源-CSDN下载 方案二 1、main.js Vue.prototype.$visitStore = async (option)=>{ //页面入参option //自己的业务逻辑 //如果是ajax,注意要加同步等待 await Vue.prototype.http.post('/customer/updateLastVisitStoreId',{lastVisitStoreId:storeId}).then(res => { console.log(res); }).catch(err => { console.log(err); }) } 2、页面 async onLoad(option) { await this.$visitStore(option);//同步执行这个方法 } 转载自:https://www.lervor.com/archives/128/ |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |