因为异步的关系所以app.js onLunch wx.request的内容可能在page执行的时候还没有获取到
所以要使用callback
参考:https://blog.csdn.net/weixin_30695195/article/details/97652048
app.js
//app.js App({ siteInfo: require("siteinfo.js"), util: require("company_applet/resource/js/util.js"), onLaunch: function () { // 展示本地存储能力 var logs = wx.getStorageSync('logs') || [] logs.unshift(Date.now()) wx.setStorageSync('logs', logs) // 登录 wx.login({ success: res => { // 发送 res.code 到后台换取 openId, sessionKey, unionId } }) // 获取用户信息 wx.getSetting({ success: res => { if (res.authSetting['scope.userInfo']) { // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框 wx.getUserInfo({ success: res => { // 可以将 res 发送给后台解码出 unionId this.globalData.userInfo = res.userInfo // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回 // 所以此处加入 callback 以防止这种情况 if (this.userInfoReadyCallback) { this.userInfoReadyCallback(res) } } }) } } }) wx.request({ url: this.siteInfo.siteroot + "?i=" + this.siteInfo.acid+"&from=wxapp&c=entry&a=wxapp&do=get_baseset", data: { m: "company_applet", uniacid: this.siteInfo.uniacid, }, header: { 'content-type': 'application/json' }, success: res => { this.globalData.baseInfo = res.data.baseset; if (this.baseDataCallback) { this.baseDataCallback(res.data.baseset); } } }) }, globalData: { userInfo: null, baseInfo:null, } })
page
// company_applet/index/index.js var app = getApp(), WxParse = require("../../wxParse/wxParse.js"); Page({ data: { baseInfo: [], getGlobalData: false, recomment_case:'', banner:[], base_url: app.siteInfo.baseUrl, }, onLoad: function (options) { var t = this, uniacid = app.siteInfo.uniacid; //get base set if (app.globalData.baseInfo && app.globalData.baseInfo != null) { this.setData({ getGlobalData: true, baseInfo: app.globalData.baseInfo }); }else{ app.baseDataCallback = getGlobalData => { if (getGlobalData != false) { this.setData({ getGlobalData: true, baseInfo: app.globalData.baseInfo }); } } } app.util.request({ url:"entry/wxapp/index", data:{ m:"company_applet", uniacid: uniacid }, success: function (e) { t.setData({ banner: e.data.banner, recomment_case: e.data.recomment_case, }); } }); } })