Do you know the way page parameters are passed in the small program

There are mainly the following ways

  • Url and the cords
  • EventChannel EventChannel
  • The local store
  • Apply global variables
  • Public variables

Url and the cords

The mode is the same as that on the Web.

Index1 page

<navigator url="/pages/index2/index2? Name = one Piece">Page 2</navigator>
Copy the code

or

    wx.navigateTo({
      url: "/pages/index2/index2? Name = one Piece"
    })
Copy the code

Index2 page

  onLoad: function (options) {
    console.log(options);// {name: One Piece}
  },
Copy the code

Note that if index2 is a Tabbar page, then you cannot get the page parameters in onLoad

EventChannel EventChannel

If a page is opened by another page via wx.navigateTo, a data channel will be established between the two pages:

  • The opened page can passthis.getOpenerEventChannel()Method to get oneEventChannelObject;
  • wx.navigateTosuccessThe callback also contains oneEventChannelObject.

The two EventChannel objects can send and listen for events to each other using the EMIT and ON methods.

index1.wxml

<view>Data from page 2: {{MSG}}</view>
Copy the code

index1.js

Page({
  data: {
    msg: ""
  },
  onLoad: function () {
    // 1 goes to page 2
    wx.navigateTo({
      url: "/pages/index2/index2".// 2 Gets the event channel object in the successful callback function
      success: ({ eventChannel }) = > {
        // 3 Listen for custom events
        eventChannel.on("data".(e) = > {
          // 4 Get the data Settings from page 2 into data
          this.setData({
            msg: e.name }) }) } }); }})Copy the code

index2.js

Page({
  onLoad: function () {
    // The page opened with wx.navigatorTo gets an event channel object
    const EventChannel = this.getOpenerEventChannel();
    // Trigger events and pass parameters to page 1
    EventChannel.emit("data", { name: One Piece}); }})Copy the code

The local store

The local storage in the applet is similar to that in the Web, which can obtain and store data in the entire application

index1.js

wx.setStorageSync('data', {name:One Piece});// Can store any type of data directly
Copy the code

index2.js

wx.getStorageSync('data');/ / to get
Copy the code

Apply global variables

Different pages are in a common application, which can be understood as app.js

app.js

Public data can be defined here

App({
  myData: {
    name: "The wu is empty"}})Copy the code

index1.js

This can be obtained via getApp on the page

    let app = getApp();
    console.log(app.myData);
Copy the code

Of course, you can modify it directly

    let app = getApp();
    app.myData.name="Eight quit";
Copy the code

Public variables

Define a separate JS file and store the data in it

common.js

const data = {
  name: One Piece
};

module.exports = data;
Copy the code

index1.js

const data = require(".. /.. /common");
Page({
  onLoad: function () {
    console.log(data); }})Copy the code

Understand the applause.