场景描述
某些情况下,开发者可能需要实现页面间的消息传递来获取数据,例如A页面跳转至B页面后,B页面发送消息给A页面,A页面能够接收到。此时可以通过消息通道的机制来实现页面间的相互通信。
实现思路
页面messageChannel创建了消息通道,并接收消息。跳转到页面test,在页面test通过消息通道发送消息。页面messageChannel收到消息后通过toast展示出来。
解决方法
页面messageChannel.ux文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
< template > < div class = "item-container" > < input type = "button" onclick = "creatChannel" value = "创建消息通道" /> < input type = "button" onclick = "routeChannel" value = "跳转到detail页面发送消息" /> < input type = "button" onclick = "cancelChannel" value = "关闭消息通道" /> </ div > </ template > < style > .item-container { margin-bottom: 50px; flex-direction: column; justify-content:center; } input{ margin-bottom: 70px; } </ style > < script > import prompt from '@system.prompt' import router from "@system.router" var channel; export default { data: { componentName: 'messageChannel' }, onInit: function () { this.$page.setTitleBar({text: 'messageChannel'}) }, creatChannel: function () { channel = new BroadcastChannel('channel1'); prompt.showToast({message: '创建消息通道成功'}); channel.onmessage = function (event) { console.log(event.data) prompt.showToast({message: '接受消息:' + event.data}); } }, routeChannel: function () { router.push({ uri: '/Test' }); }, cancelChannel: function () { channel.close(); prompt.showToast({message: '关闭消息通道成功'}); } } </ script > |
页面test.ux文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
< template > < div class = "item-container" > < input type = "button" onclick = "postChannel" value = "发送消息" /> </ div > </ template > < style > .item-container { margin-bottom: 50px; flex-direction: column; justify-content:center; } </ style > < script > export default { data: { componentName: 'detail', }, onInit: function () { this.$page.setTitleBar({text: 'detail'}) }, postChannel: function () { var channel = new BroadcastChannel('channel1'); channel.postMessage("hello world"); } } </ script > |
更多参考
快应用文档参考:
https://developer.huawei.com/consumer/cn/doc/development/quickApp-References/quickapp-script
原文链接:developer.huawei.com/consumer/cn…
原作者:Mayism