第一种(在跳转页面时使用URL编程式传参)
单向传递:只能上级页面传递到下级页面
注意:这种方法不适用传递大量的数据,传递的数据只能是string类型,如果想要传递对象或数组则需要使用JSON.stringify进行转换。
不适合用在uni.navigateBack(不携带跳转路由)
上级页面(通过URL传递数据)注意:后面拼接参数中不能存在空格,否则无法传递的参数为字符串属性
preserveRevise(){
uni.navigateTo({
url:'/pages/addressMange/addressMange?id=1'
})
}
下级页面(通过onLoad接收数据)
onLoad(e){
console.log(e.id);
}
双向传递:上级页面可以传递给下级页面,下级页面也可以传递给上级页面
上级页面(使用events,利用下级页面向上级页面传递数据的变量名获取传递的参数)
preserveRevise(){
uni.navigateTo({
url:'/pages/addressMange/addressMange?id=1',
events:{
//获取下级页面传递回来的参数
sonPageData:data=>{
console.log(data);
}
}
})
}
下级页面(利用this.getOpenerEventChannel().emit向上级页面传递参数的变量名和变量值)
onLoad(e){
console.log(e.id);
this.getOpenerEventChannel().emit('sonPageData',"我是第二个页面传递回来的数据")
}
第二种
利用uni.setStorageSync和uni.getStorageSync进行数据的缓存和取出以及最后对缓存数据的销毁
上级页面(对需要传递的数据进行数据缓存)
注意:缓存的数据必须为字符串形式,对象或数组需要先进行转换
let item = JSON.stringify(this.userInfo[e])
uni.setStorageSync('userInfo',item)
下级页面(对缓存的数据进行取出并且进行销毁)
onLoad() {
console.log("进入了编辑地址页面");
var data = uni.getStorageSync('userInfo')//取出缓存数据
var res = JSON.parse(data)
this.userInfo = res
uni.removeStorageSync('userInfo')
var data = uni.getStorageSync('userInfo')//销毁缓存数据
console.log(data);
}
第三种
利用uni.$emit 和 uni.$on进行跨页面传值
传递值页面(使用uni.$emit传递值的变量名和变量值)
uni.$emit('addUserInfo',this.userInfo)
接收值页面(在onload周期中使用uni.$on接收已经传递的参数)
uni.$on('addUserInfo',res=>{
console.log(res);
})
注意:uni.$emit 和 uni.$on属于全局跨页面传参,在接收值页面要在onUnload周期添加移除监听时间。
onUnload() {
uni.$off('addUserInfo')
}