小程序傳遞參數(shù)的方式有三種:
(1)通過在App.js中設(shè)置全局變量
(2)通過拼接URL直接傳遞
(3)通過數(shù)據(jù)緩存存儲再獲取
1.app.js
通常把不會更改的數(shù)據(jù)放在app.js的Data中,在各個頁面中都可以通過APP實(shí)例獲取Data數(shù)據(jù)。
var app = getApp(); var data = app.data;
2.wx.navigateTo({})中URL攜帶參數(shù)
wx.navigateTo({
url: 'test?id=1'
}); |
3. 數(shù)據(jù)緩存
①wx.setStorageSync(KEY,DATA)存儲數(shù)據(jù)
try {
wx.setStorageSync('key', 'value')
} catch (e) {
} |
②wx.getStorageSync(KEY)獲取數(shù)據(jù)
try {
var value = wx.getStorageSync('key')
if (value) {
// Do something with return value
}
} catch (e) {
// Do something when catch error
} |
然而,根據(jù)所傳遞參數(shù)的數(shù)據(jù)類型的不同,如對象、數(shù)組集合需要進(jìn)行相應(yīng)的處理。本質(zhì)上都是String類型的傳遞。
1、傳遞基本數(shù)據(jù)類型
Page({
data: {
testStr: 'xiaochengxu'
},
next: function(e){
wx.navigateTo({
url: '/test/test?str='+this.data.testStr
})
}
})
Page({
onLoad:function(options){
console.log("接收到的參數(shù)是str="+options.str);
}
}) |
打印內(nèi)容:接收到的參數(shù)是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("接收到的參數(shù)是testData="+options.testData);
this.data.testData = JSON.parse(options.testData);
}}) |
打印內(nèi)容:
接收到的參數(shù)是testData={"name":"username","password":"password"}
3,傳遞數(shù)組集合
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("接收到的參數(shù)是list="+options.list);
this.data.list = JSON.parse(options.list);
}}) |
打印內(nèi)容:接收到的參數(shù)是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]);
}
}
}
} |