我在app.js文件里加了如下代码:
// 全局openid
wx.cloud.callFunction({
name: ‘login’
}).then(res=> {
this.openid = res.result.openid
})
然后在某个页面下加了如下代码:
var global = getApp()
console.log(global)
然后在控制台可以看到已经获取到全局的对象了
然后我尝试把代码改成如下,就报错了,显示undefined,我留意到控制台输出undefined是在最开始的位置,不知道跟异步有没有关系:
var global = getApp()
console.log(global.openid)
————————————————————————
更新:
我把app.js里面的代码改成如下:
wx.cloud.callFunction({
name: ‘login’
}).then(res=> {
this.openid = res.result.openid
})
this.test = ‘123’
然后再访问,却是可以的。。。
全局变量最好放globalData里
app.js
loginByCloud(callback){
if(this.globalData.openid && this.globalData.openid != ‘’){
return callback ? callback(this.globalData.openid) : void 0
}
wx.cloud.callFunction({
name: 'login'
}).then(res=> {
this.globalData.openid = res.result.openid
callback && callback(res.result.openid)
})
}
==========================
页面js
let app = getApp()
Page({
onLoad(){
app.loginByCloud(function(openid){
console.log(‘登录成功’, openid, app.globalData.openid)
})
}
})
我常用的方案:app.js:
//获取openid不保存在缓存 getOpenidOnlyCloud: async function () { return this.globalData.openid = this.globalData.openid || (await wx.cloud.callFunction({ name: 'login' })).result.OPENID }, //获取openid后保存在缓存 getOpenid: async function () { if (this.globalData.openid) return this.globalData.openid let openid = wx.getStorageSync( 'openid' ) if (openid) return this.globalData.openid = openid wx.setStorageSync( 'openid' , this.globalData.openid = (await wx.cloud.callFunction({ name: 'login' })).result.OPENID) return this.globalData.openid }, |
其他page里:
onLoad: async function () { this .openid = await app.getOpenid() }, |
云函数login:
const cloud = require( 'wx-server-sdk' ) cloud.init() exports.main = (event) => { return { ...event,...cloud.getWXContext()} } //可同时支持返回openid和处理cloudID |