uni-app官方文档
父页面跳转子页面传参
- uni.navigateTo(OBJECT)
保留当前页面,跳转到应用内的某个页面,使用uni.navigateBack可以返回到原页面。 - uni.navigateBack(OBJECT)
关闭当前页面,返回上一页面或多级页面。可通过 getCurrentPages() 获取当前的页面栈,决定需要返回几层。
//在起始页面跳转到test.vue页面并传递参数
uni.navigateTo({
url: 'test?id=1&name=uniapp'
});
//在test.vue页面接受参数
export default {
onLoad: function (option) { //option为object类型,会序列化上个页面传递的参数
console.log(option.id); //打印出上个页面传递的参数。
console.log(option.name); //打印出上个页面传递的参数。
}
}
子页面返回父页面传参
项目使用场景:主页面(传递参数)跳转A页面,A页面跳转B页面。当B页面返回A页面时,从主页面传递的参数需要再次返回给A,所以需要A页面跳转B页面时传递该参数,B页面再返回给A。
使用uni.$emit和uni.$on页面通讯
- uni.$emit(eventName,OBJECT)
触发全局的自定义事件,附加参数都会传给监听器回调函数。 - uni.$on(eventName,callback)
监听全局的自定义事件,事件由 uni.$emit 触发,回调函数会接收事件触发函数的传入参数。 - uni.$off([eventName, callback])
移除全局自定义事件监听器。
//官网API
//在子页面定义事件传参
uni.$emit('update',{msg:'页面更新'})
//在父页面接受参数
export default {
onLoad: function () {
uni.$on('update',function(data){
console.log('监听到事件来自 update ,携带参数 msg 为:' + data.msg);
})
}
}
//引用示例
//从A跳转B页面,B页面返回A页面时传参
//B页面
uni.$emit("targetEvent",{shiftOverId:that.shiftOverId,productOrderId:that.productOrderId })
uni.navigateBack();
//A页面
onLoad: function (e) {
uni.$on("targetEvent",(e)=>{
this.preId = JSON.parse(e.shiftOverId)
this.productOrderId = JSON.parse(e.productOrderId)
uni.$off('targetEvent')
})
},