Foreword
When we use uni-app to develop front-end projects, we will encounter requirements that need to request the interface to return results in onLaunch, and this result may be used in the onLoad of each page of the project, such as WeChat applet login in onLaunch After obtaining the openid and obtaining the token, each page of the project needs to bring the token to request other interfaces. However, the request in onLaunch is asynchronous, that is to say, the page onLoad starts to execute after onLaunch is executed, instead of waiting for onLaunch to return data asynchronously before executing, which causes the page to be unable to get the data obtained asynchronously in onLaunch
solution
1. Add the following code in main.js
Vue.prototype.$onLaunched = new Promise(resolve => {
Vue.prototype.$isResolve = resolve
})
2. Add code this.$isResolve()
in onLaunch of App.vue
onLaunch() {
// #ifdef MP-WEIXIN
let that = this;
uni.login({
provider:'weixin',
success: function(loginRes) {
that.$api.getOpenid({
code: loginRes.code,
}).then(result => {
uni.setStorageSync("openid", result.data);
uni.setStorageSync("session_key", result.session_key);
uni.setStorageSync("qy_id", result.ent_id);
uni.setStorageSync("user_type", result.type_id);
that.$isResolve();
});
}
});
// #endif
}
3. Add code await this.$onLaunched
in the page onLoad
async onLoad(option) {
await this.$onLaunched
let token =''
try {
token = uni.getStorageSync('mcToken')
} catch(e) {
console.error(e)
}
// Now you can use token to call other related interfaces
}
Post comment 取消回复