看uniapp文档的例子,感觉不是很明白,navigateTo里面的events和success回调函数,官网给的例子也不是很完整,于是为了搞清楚,自己写了个小例子,去打印看看数据是究竟怎么回事。 废话不多说,直接上代码!
// index.vue
<template>
<view>
<view>msg:{{fdata.msg}}</view>
<view>title:{{title}}</view>
<button @click="toTestPage">go to test page</button>
</view>
</template>
<script>
export default {
data() {
return {
fdata: {
msg: ''
},
title: '我是index的数据'
}
},
methods: {
toTestPage() {
const that = this
uni.navigateTo({
url: '/pages/test/test1',
events: {
recive: function(data) {
that.fdata = data.data
console.log("index:已接受!",that.fdata)
}
},
success: function(res) {
res.eventChannel.emit('send', {
data: {
msg:'index给test数据:' + that.title,
title: that.title
}
})
}
})
}
}
}
</script>
// test1.vue
<template>
<view>
<view>msg:{{fdata.msg}}
</view>
<view>title:{{title}}</view>
<button @click="toIndexPage">go to index page</button>
</view>
</template>
<script>
export default {
data() {
return {
fdata: {
msg: ''
},
title: '我是test1的数据'
}
},
onLoad() {
const that = this
const eventChannel = this.getOpenerEventChannel();
eventChannel.on('send', function(data) {
that.fdata = data.data
console.log("test:收到index",that.fdata,that.fdata.msg)
})
eventChannel.emit('recive', {
data: {
msg: 'test给index' + that.title,
title: 'test:index请接收'
}
});
},
methods: {
toIndexPage() {
uni.navigateBack({
delta: 1
})
}
}
}
</script>
效果图:
- 刚开始的页面,msg没有数据
-
点击按钮去到test的页面,触发监听事件,test接收到了index的数据msg,并显示出来
-
点击按钮/头部返回按钮,回到index页面,index页面接收了test发过来的数据
⚠️注意:要用navigateBack返回,index页面才会存留着接收test的数据,要是用navigateTo是没有存留的。