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

angryTom
Release: 2020-03-28 09:15:57
Original
12678 people have browsed it

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"
   }
})
Copy after login

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,
    });
  }
})
Copy after login

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)
  }
})
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!