第一种(在跳转页面时使用URL编程式传参)
1.1 单向传递:只能上级页面传递到下级页面
提示: 这种方法不适用传递大量的数据,传递的数据只能是string类型,如果想要传递对象或数组则需要使用JSON.stringify进行转换。但uni.navigateBack不能传参,因为它不携带跳转路由
上级页面(通过URL传递数据)
click(){
uni.navigateTo({
url:'/pages/service/service?nicheng='+gongsi+'&&text='+this.text'
})
}
下级页面(通过onLoad接收数据)
onLoad(e){
console.log(this.nicheng);
console.log(this.text);
}
1.2 双向传递:上级页面可以传递给下级页面,下级页面也可以传递给上级页面
上级页面(使用events,利用下级页面向上级页面传递数据的变量名获取传递的参数)
click(){
uni.navigateTo({
url:'/pages/test/test?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 obj = JSON.stringify(this.userInfo[e])
uni.setStorageSync('userInfo',obj)
接收值页面(对缓存的数据进行取出并且进行销毁)
onLoad() {
var data = uni.getStorageSync('userInfo')//取出缓存数据
var res = JSON.parse(data)
this.userInfo = res
uni.removeStorageSync('userInfo')//销毁缓存数据
console.log(data);
}
第三种 (利用uni.
on进行跨页面传值)
传递值页面(使用uni.$emit传递值的变量名和变量值)
uni.$emit('UserInfo',this.userInfo)
由于uni.
on属于全局跨页面传参,所有在接收值页面要在onUnload周期添加移除监听事件。
onUnload() {
uni.$off('UserInfo')
}