Home >WeChat Applet >Mini Program Development >A brief discussion on two methods of transferring values ​​between pages in mini programs

A brief discussion on two methods of transferring values ​​between pages in mini programs

青灯夜游
青灯夜游forward
2021-05-08 09:45:162654browse

This article will introduce to you two methods of value transfer between pages in WeChat mini programs. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

A brief discussion on two methods of transferring values ​​between pages in mini programs

1: url transfer with parameters

Like front-end languages, transfer between mini program pages You can add parameters after the routing url, and the parameters will be passed to the new page during routing.

index.wxml:

<!--index.wxml-->
<view class="container">
  <!-- 使用navigator组件 -->
  <navigator url="../demo/demo?title=参数传递">title=参数传递</navigator>
</view>

demo.js

// pages/demo/demo.js
Page({
 
  data: {
    title:&#39;&#39;
  },
 
  onLoad: function (options) {
    console.log(options)  //打印options,可以看到title的值可以获取到
    this.setData({
      title:options.title  //为页面中title赋值
    })
  },
 
})

demo.wxml

<!--pages/demo/demo.wxml-->
<view class=&#39;container&#39;>
  {{title}}
</view>

Rendering:

           

Two: Will Values ​​are stored in global variables

We can also store the required values ​​​​in global variables and directly reference them where needed.

app.js

//app.js
App({
  globalData: {}
})

index.wxml

<!--index.wxml-->
<!-- 点击触发goto_demo函数 -->
<view class="container" bindtap=&#39;goto_demo&#39;> 
  title=参数传递
</view>

index.js

//index.js
//获取应用实例
const app = getApp()
 
Page({
  data: {
    title:&#39;参数传递&#39;
  },
 
  goto_demo: function() {
    app.globalData.title = this.data.title
    wx.navigateTo({
      url: &#39;../demo/demo&#39;,
    })
  }
})

demo.js

// pages/demo/demo.js
//获取应用实例
const app = getApp()
 
Page({
 
  data: {
    title:&#39;&#39;
  },
 
  onLoad: function (options) {
    console.log(app.globalData.title)  //打印options,可以看到title的值可以获取到
    this.setData({
      title: app.globalData.title  //为页面中title赋值
    })
  },
 
})

Required When using global variables, remember to get the application instance first: const app = getApp()

The rendering is the same as above.

Related learning recommendations: Small Program Development Tutorial

The above is the detailed content of A brief discussion on two methods of transferring values ​​between pages in mini programs. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete