微信小程式中的變數和作用域
阿新 • • 發佈:2019-02-05
一,全域性變數
在app.js裡的變數和方法是全域性的。
//app.js App({ 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) } } }) } } }) }, globalData: { userInfo: null, basePath: 'http://127.0.0.1:8086' } })
在其他頁面上,可以通過getApp()獲取到裡面的方法和變數,console出來後:
如果要拿到我們提前設定的basePath,我們可以這樣:
var app=getApp();
var basePath = app.globalData.basePath;
獲取使用者的登入資訊或者其他方法亦是如此;
二,區域性頁面內的資料互動
區域性頁面上的所有資料,都源於js內的data物件:
在頁面上,可直接使用data內的資料;
賦值:
areaChange:function(e){ //這裡獲取到了陣列角標 console.log(e.detail.value) var index1 = e.detail.value this.setData({ index: index1 }) // console.log("地區:" + this.data.areaListArray[index1]) console.log(this.data.areaList[index1]) console.log(this.data.areaIdList[index1]) }
在方法內,可以直接使用this.setData()定義變數並賦值,只有這樣定義的變數能在整個頁面內使用。
onLoad: function (options) { var that = this; var app=getApp(); console.log(app); var basePath = app.globalData.basePath; wx.request({ method:"GET", url: basePath +'/area/getAreaByLevel?level=1', success: function (res) { console.log(res); var areaListArray = []; var areaPkIdArray = []; for(var index in res.data.data){ areaListArray.push(res.data.data[index].area) areaPkIdArray.push(res.data.data[index].pkId) } that.setData({ // projectList : res.data.data.data, // fileUrl: res.data.data.fileSystem areaList: areaListArray, areaIdList: areaPkIdArray }) }, fail: function (res) { console.log(res); } }) },
如果有this指向不明的,可先將this賦值給其他變數,再進行使用。
本例中是將this賦值給了that,然後再使用的。