uni-app开发微信小程序踩坑记录

2022年2月17日星期四 bugLog

问题描述

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

# 解决方案

第一步main.js 中增加如下代码:

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

第二步 在 App.vue 的 onLaunch 中增加代码 this.$isResolve(),具体如下:

onLaunch () {
    // #ifndef H5
    uni.login({
        success: loginRes => {
            // #ifdef MP-WEIXIN
            login({ // 该接口为我们自己写的获取 openid/token 的接口,请替换成自己的
                appId: 'wx1234567890',
                code: loginRes.code
            }).then(res => {
                try {
                    console.info(res.object.token)
                    uni.setStorageSync('mcToken', res.object.token)
                    this.$isResolve()
                } catch (e) {
                    console.error(e)
                }
            })
            // #endif
        }
    })
    // #endif
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

步骤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
2
3
4
5
6
7
8
9
10
11
12
Last Updated: 6/17/2022, 3:21:49 PM