Scenario Description In some cases, the developer may need to implement inter-page messaging to retrieve data. For example, after page A jumps to page B, page B sends A message to page A, which can be received by page A. At this time, we can realize the mutual communication between pages through the mechanism of message channel.
The implementation idea page MessageChannel creates the messageChannel and receives the message. Jump to page Test, where you send a message through the message channel. The page MessageChannel receives the message and presents it through Toast.
The solution page messageChannel.ux file:
<template> <div class="item-container"> <input type="button" onclick="creatChannel" value=" "/> <input <input type="button" onClick ="cancelChannel" /> <input type="button" onClick ="cancelChannel" /> </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: 'Message channel created successfully '}); Channel.onMessage = function (event) {console.log(event.data) Prompt. ShowToast ({message: 'Recepting message:' + event.data}); } }, routeChannel: function () { router.push({ uri: '/Test' }); }, cancelChannel: function () { channel.close(); Prompt. ShowToast ({message: 'Message channel closed successfully '}); } } </script>
Page test.ux file:
<template> <div class="item-container"> <input type="button" onclick="postChannel" value=" send message "/> </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>
More references to the fast application document reference:
https://developer.huawei.com/…
The original link: https://developer.huawei.com/… Author: Mayism