前言

我们在用 uni-app 开发前端项目时,会遇到需要在 onLaunch 中请求接口返回结果,并且此结果在项目各个页面的 onLoad 中都有可能使用到的需求,比如微信小程序在 onLaunch 中进行登录后取得 openid 并获得 token,项目各页面需要带上该 token 请求其他接口。但是,onLaunch 中的请求是异步的,也就是说在执行 onLaunch 后页面 onLoad 就开始执行了,而不会等待 onLaunch 异步返回数据后再执行,这就导致了页面无法拿到 onLaunch 中异步获取的数据

解决方案

1.main.js中增加如下代码

Vue.prototype.$onLaunched = new Promise(resolve => {
    Vue.prototype.$isResolve = resolve
})

2.App.vue的 onLaunch 中增加代码 this.$isResolve()

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.页面 onLoad 中增加代码 await this.$onLaunched

async onLoad(option) {
    await this.$onLaunched

    let token = ''
    try {
        token = uni.getStorageSync('mcToken')
    } catch(e) {
        console.error(e)
    }

    // 下面就可以使用 token 调用其他相关接口
}
点赞(1)

评论列表 共有 0 评论

暂无评论

微信服务号

微信客服

淘宝店铺

support@elephdev.com

发表
评论
Go
顶部