微信小程序 閉包寫法詳細介紹
微信小程序 閉包寫法
在入口處的 app.js 中定義了一個獲取用戶 OpenId 的函數(shù),在微信的登錄接口 wx.login 中發(fā)起網(wǎng)絡(luò)請求。這個函數(shù)傳入一個回調(diào)函數(shù) cb
getOpenIdData: function(cb) { var that = this //調(diào)用登錄接口 wx.login({ success: function(res) { wx.request({ url: 'https://api.weixin.qq.com/sns/jscode2session', data: { appid: "wx6224eb*********", secret: "879b58fc64bc5**************", js_code: res.code, grant_type: "authorization_code" }, success: function(res) { // 保存到全局變量中 that.globalData.openid = res["data"]["openid"] cb(that.globalData.openid) }, fail: function() { console.log("request error") } }) } }) }
在 index.js 文件時,使用 getOpenIdData 接口
var app = getApp() app.getOpenIdData(function(openid){ //回調(diào)更新數(shù)據(jù) that.setData({ openid: openid }) })
在接口中傳入匿名函數(shù)
function(openid){ //回調(diào)更新數(shù)據(jù) that.setData({ openid: openid }) }
先將匿名函數(shù)傳入到 app.js 中,獲取到 openid 數(shù)據(jù)。再回到 index.js 將數(shù)據(jù)賦給此文件的全局變量。這樣就實現(xiàn)跨文件傳遞數(shù)據(jù)。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
js c++ vue方法與數(shù)據(jù)交互通信示例
這篇文章主要為大家介紹了js c++ vue方法與數(shù)據(jù)交互通信示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08WindiCSS實現(xiàn)加載windi.config.ts配置文件詳解
這篇文章主要為大家介紹了WindiCSS實現(xiàn)加載windi.config.ts配置文件詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-02-02