赞
踩
在小程序中,我们一般在onLaunch中发起登录请求,由于是请求是异步的,在onLoad之后才执行完登录请求,如果在onLoad中需要使用请求后的数据,会发现取不到值,以下是一些解决方式,可以按自己所需使用。
// app.js onLaunch () { wx.login({ success: result => { wx.request({ url: 'test.php' // 示例 data: {...}, success: res => { this.globalData.openId = res.data.openId // 回调 if (this.loginCallback) this.loginCallback(res.data) }, fail: err => { // 需要的话请求失败处也可以使用回调 } }) } }) } // page.js onLoad () { const app = getApp() if (app.globalData.openId) { // do something } else { app.loginCallback = (data) => { // do something } } }
// app.js App({ initLogin () { return new Promise((resolve, reject) => { wx.login({ success: result => { wx.request({ url: 'test.php' // 示例 data: {...}, success: res => { resolve(res.data) }, fail: err => { reject('error') } }) } }) }) } }) // page.js onLoad () { const app = getApp() app.initLogin().then(res => { // do something }).catch(err => {}) }
// app.js watch (method) { let obj = this.globalData // 这里监听 openId Object.defineProperty(obj, "openId", { configurable: true, enumerable: true, set: function (value) { method(value) // 触发页面回调函数 } }) }, onLaunch () { wx.login({ success: result => { wx.request({ url: 'test.php' // 示例 data: {...}, success: res => { this.globalData.openId = res.data.openId } }) } }) } // page.js onLoad () { const app = getApp() app.watch(this.watchBack) } watchBack (openId) { if (openId) { // do something } }
// app.js onLaunch () { wx.login({ success: result => { wx.request({ url: 'test.php' // 示例 data: {...}, success: res => { const currentPage = wx.getCurrentPages()[0] // 触发当前页的init方法 currentPage.init(res.data) } }) } }) } // page.js init (data) { // do somethine }
// app.js onLaunch () { wx.login({ success: result => { wx.request({ url: 'test.php' // 示例 data: {...}, success: res => { // 请求结果存到了storage里,再跳到页面可以获取到storage里的数据 wx.reLaunch({ url: '/pages/n-index/n-index', }) } }) } }) }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。