在做小程序时,需要将一个有页面的数据传到另一个页面的js中使用,这里使用的方法就是通过小程序中的app.js存储,然后在另一个js中取出来使用。
将需要使用的变量存储到app.js中。globalData用于存储变量。
this.globalData = {
}
在需要存储的js中,将从接口取出的数据存入到globalData中。
success: function (res) {
console.log(res);
that.setData({
//将接口返回的数据data赋值给data
data:res.data,
})
app.globalData=res.data;
//console.log(app.globalData)
},
fail: function (res) {
console.log("fail=================")
},
然后在另一个js页面中取出,先设置app
const app = getApp();
然后在该页面中对取出的数据进行使用。直接使用app.globalData即可。
var temperature=[];
var date=[];
for (var i = 0; i < app.globalData.length; ++i) {
temperature[i]=app.globalData[i].temperature;
date[i]=app.globalData[i].date;
}
还有另一种传递值的方法就是通过url加变量传递。
跳转时将数据拼接在URL后面;在另一个页面的onLoad()方法的参数中即可获取到传递的参数。
//first.js
wx.navigateTo({
url: `../select/select?id=${id}`,
})
//select.js
onLoad(option){
const id = option.id;
}
如果将对象类型的数据拼接在路径后面,到另一个页面获取时会发现是"[object,object]",无法使用。
解决方法:利用JSON.stringify()和JSON.parse()。
//传递数据的页面
const selectData = JSON.stringify(this.data.selectData);
wx.redirectTo({
url: `../order/order?selectData=${selectData}`
})
//接收数据的页面
onLoad(option){
const selectData = JSON.stringify(option.selectData);
}
不同页面之间传递数据主要是这两种方法。