Home  >  Article  >  WeChat Applet  >  How to assign values ​​to global variables in WeChat applet

How to assign values ​​to global variables in WeChat applet

angryTom
angryTomOriginal
2020-03-28 09:15:5712694browse

How to assign values ​​to global variables in WeChat applet

How to assign values ​​to global variables in WeChat mini programs

Global variables in mini programs can be defined in globalData, as follows Let’s introduce how to use globalData.

Recommended learning: Small program development

1. First define global variables in app.js

App({
  onLaunch: function () {
  },
   globalData: {
     age: "18"
   }
})

2. Then in a certain To reference this global variable in the page

first declare var app=getApp(); under the file and then reference and assign the global variable.

//将全局变量的值赋给页面的一个变量
//index.js
var app = getApp()
Page({
  data: {
    age: ""
  },
  onLoad: function () {
    this.setData({
      age: app.globalData.age,
    });
  }
})

3. If you want to change the global variable, that is, reassign the value, you can write like this

//更改全局变量的值
var app = getApp()
Page({
  data: {
    age: ""
  },
  onLoad: function () {
    app.globalData.age="20"
    console.log(app.globalData.age)
  }
})

For more WeChat applet development tutorials, please pay attention to PHP Chinese website!

The above is the detailed content of How to assign values ​​to global variables in WeChat applet. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn