Scenario: When page A jumps to B, some parameters need to be brought over. Small parameters can be brought over by query. When the amount of data is large, query is not a good choice. At this time, the EventChannel
1. Theoretical premise
If a page is wx.navigateTo
, a data channel will be established between the two pages:
- The opened page can obtain a
EventChannel
objectthis.getOpenerEventChannel()
- The
success
callback of wx.navigateTo also contains an EventChannel object. - These two EventChannel objects can use the
emit
andon
methods to send and monitor events to each other.
2. Simple to use: one-way value transfer
A page:
<button bindtap="navigateToB">跳转B页面</button>
navigateToB () {
wx.navigateTo({
url: '/pages/logs/logs',
success: (res) => {
// 跳转成功后,触发事件'delivery', 并可携带数据(即第一个参数是事件名,第二个参数是数据包)
res.eventChannel.emit('delivery', {
data: '123'
})
}
})
}
Page B:
onLoad() {
// 建立数据通道
const eventChannel = this.getOpenerEventChannel()
// 监听'delivery'事件,并获取数据包
eventChannel.on('delivery', data => {
console.log('on - delivery', data)
})
}
You can see from the print result that the data has been received
Three, two-way communication
After jumping to page B, if you still need to send some data back to page A :
- In page B, the
emit
and data packets are sent; multiple events are tiled - A page
wx.navigateTo
theevents
parameters: inter-page communication interface, for monitoring is opened to send pages to the current page data
A page:
navigateToB () {
wx.navigateTo({
url: '/pages/logs/logs',
// events 用于监听下一个页面的事件 及 回传的数据包
events: {
reverseData: (data) => {
console.log('reverseData', data)
},
backData: (data) => {
console.log('backData', data)
}
},
success: (res) => {
// 跳转成功后,触发事件'delivery', 并可携带数据(即第一个参数是事件名,第二个参数是数据包)
res.eventChannel.emit('delivery', {
data: '123'
})
}
})
}
Page B:
onLoad() {
// 建立数据通道
const eventChannel = this.getOpenerEventChannel()
// 监听'delivery'事件,并获取数据包
eventChannel.on('delivery', data => {
console.log('on - delivery', data)
})
// 通过emit向上一个页面回传数据,多个事件平铺
eventChannel.emit('reverseData', {
data: '321'
})
eventChannel.emit('backData', {
data: 'abc'
})
}
Then you can happily transmit large data packets hhhh
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。