微信小程序全局变量的定义与存取

app.js里面定义全局变量

//app.js
App({
  onLaunch: function () {
    this.globalData = {
      statusBarHeight: wx.getSystemInfoSync()['statusBarHeight'],//顶部栏高度
      // "navigationStyle": "custom" 需要顶格显示的页面json文件需要加此配置
      isLogin:false
    }
  }
})

方法一、在其他页面js获取全局变量,在Page外先定义const app = getApp()

//pages/index/index.js
const app = getApp()
Page({
  data: {
    statusBarHeight: app.globalData.statusBarHeight,//从全局变量自定义顶部栏高度并赋值给当前页面变量statusBarHeight
    page_data:0,//赋值页面变量page_data=0

  },
onLoad: function (options) {
   // 页面初始化 options为页面跳转所带来的参数
console.log(options)
//发起网络请求
var that = this//不要漏了这句,把当前的状态对象存储到that变量对象中,因为this在js中是特指当前整个Page({})对象,如果中间进行其他操作this所指代的对象是会变化的

that.setData({
   statusBarHeight:200,//赋值,冒号“:”
   page_data:10//赋值
   new_data:'这是新定义的变量'// 在setData里直接设置新的参数new_data,也可以与wxml中的{{new_data}}进行数据绑定
    })
    app.globalData.statusBarHeight=300//给全局变量赋值注意这里是等于号“=”
    app.globalData.isLogin= true
    console.log(app.globalData.statusBarHeight)
  

  },

//如果wxml中需要显示变量值
// <view class="topbar" style="padding-top:{{statusBarHeight}}px">
//{{page_data}}{{new_data}}
//</view>

方法二、直接获取,跟方法一不能混用。

//pages/index/index.js
Page({
  data: {
    statusBarHeight: getApp().globalData.statusBarHeight,//

  },

下面是摘抄自简书网友的文章代码“一个好的app.js”,原文地址:https://www.jianshu.com/p/925aad432874

//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;
    }
    })
  }
  
})

基于互联网精神,在注明出处的前提下本站文章可自由转载!

本文链接:https://ranjuan.cn/weixin-global-parameter/

赞赏

微信赞赏支付宝赞赏

p20160626
php中mysql报错call-to-a-member-function-fetch_assoc-on-boolean
一般性动态磁盘数据导入恢复