WeChat applet - parameter passing
There are three ways to pass parameters to the applet:
( 1) By setting global variables in App.js
( 2 ) Pass directly by splicing URL
( 3 ) Re-acquiring through data cache storage
1.app.js
Usually , the data that will not be changed is placed in the Data of app.js , and the Data data can be obtained through the APP instance in each page .
var app = getApp ();
var data = app.data; |
2. URL carries parameters in wx.navigateTo({})
wx.navigateTo({ url: 'test?id=1'}); |
3. Data cache
① wx.setStorageSync(KEY,DATA) to store data
try { wx.setStorageSync('key', 'value') } catch (e) { } |
② wx.getStorageSync(KEY) to get data
try { var value = wx.getStorageSync('key') if (value) { // Do something with return value } } catch (e) { // Do something when catch error } 或 wx.getStorage({ key: 'key', success: function(res) { console.log(res.data) }
}) |
然而,根据所传递参数的数据类型的不同,如对象、数组集合需要进行相应的处理。本质上都是String类型的传递。
1、传递基本数据类型
Page({ data: { testStr: 'xiaochengxu' }, next: function(e){ wx.navigateTo({ url: '/test/test?str=' + this.data.testStr }) } }) |
Page({ onLoad:function(options){ console.log("接收到的参数是str = "+options.str); } }) |
打印内容:接收到的参数是str=xiaochengxu
2,传递对象
Page({ data: { testData:{name:'username', password:'password'} }, next: function(e){ wx.navigateTo({ url: '/test/test?testData='+JSON.stringify(this.data.testData) }) } }) |
Page({ data:{ testData:null }, onLoad:function(options){ console.log("接收到的参数是testData="+options.testData); this.data.testData = JSON.parse(options.testData); }}) |
打印内容:
接收到的参数是testData={"name":"username","password":"password"}
3,传递数组集合
Page({ data: { list:['item-A','item-B'] }, next: function(e){ wx.navigateTo({ url: '/test/test?list='+JSON.stringify(this.data.list), }) } }) |
Page({ data:{ list:[] }, onLoad:function(options){ console.log("接收到的参数是list="+options.list); this.data.list = JSON.parse(options.list); }}) |
打印内容:接收到的参数是list=["item-A","item-B"]
统一处理:
var dealParam = function(data) { for(var i in data) { if (typeof data[i] == ‘string’){ console.log(“key=”+i+“; value=”+data[i]); } else if (typeof data[i] == ‘object’) { dealParam(data[i]); } }
} |