微信小程序 全局变量

参考文章

小程序全局变量

怎样更改微信小程序全局变量 :app.globalData.XX = xx就可以,setData不行,app对象没这个方法.
如果app这个变量指的是getApp(),即app.js,那么是可以通过=去赋值的,如果app是page里面的this,那么就需要使用setData去对数据进行赋值

step 1 声明 or 定义

// in app.js
globalData:{    
    userInfo:null,    
    test:"test"    
}  

修改全局变量

//获取手机信息
  getSys:function() {
    var that = this;
    //  这里要非常注意,微信的scroll-view必须要设置高度才能监听滚动事件,所以,需要在页面的onLoad事件中给scroll-view的高度赋值
    wx.getSystemInfo({
    success: function(res) {
//设置变量值
      that.globalData.sysInfo=res;  //直接使用this就可以调用本页面的全局变量
      that.globalData.windowW=res.windowWidth;
      that.globalData.windowH=res.windowHeight;
    }
    })
  }

step 2 跨页面调用

var app = getApp();//写在页面顶部page()外
// in page.js
app.globalData.test="123"  //修改值直接使用“=”

step 3 自查需要注意的点

微信小程序 全局变量_第1张图片
官网图片

一个好的app.js

小程序中经常需要使用该设备的信息以及用户的信息,所以app.js最好这样写:

//app.js
App({
//全局变量
  globalData:{
    userInfo:null,
    sysInfo:null,
    windowW:null,
    windowH:null
  },
  //启动
  onLaunch: function () {
    // 获取用户信息
   this.getUserInfo();
   this.getSys();
  },
  //获取用户信息
 getUserInfo:function(cb){
    var that = this
    wx.login({
      success: function () {
        wx.getUserInfo({
          success: function (res) {
            that.globalData.userInfo = res.userInfo
            console.log(res.userInfo);
            typeof cb == "function" && cb(that.globalData.userInfo)
          }
        })
      }
    })
  },
  //获取手机信息
  getSys:function() {
    var that = this;
    //  这里要非常注意,微信的scroll-view必须要设置高度才能监听滚动事件,所以,需要在页面的onLoad事件中给scroll-view的高度赋值
    wx.getSystemInfo({
    success: function(res) {
      console.log(res.model)
      console.log(res.pixelRatio)
      console.log(res.windowWidth)
      console.log(res.windowHeight)
      console.log(res.language)
      console.log(res.version)
      console.log(res.platform)
//设置变量值
      that.globalData.sysInfo=res;
      that.globalData.windowW=res.windowWidth;
      that.globalData.windowH=res.windowHeight;
    }
    })
  }
  
})

至此,完成

你可能感兴趣的:(微信小程序 全局变量)