Scene description

In some cases, the developer may need to transfer messages between pages to obtain data. For example, after page A switches to page B, page B sends A message to page A, and Page A receives the message. At this point, the communication between pages can be realized through the mechanism of message channel.

Implementation approach

The page messageChannel creates the messageChannel and receives the message. Go to test and send messages through the message channel on test. The page messageChannel receives the message and is displayed through toast.

The solution

Page Messagechannel.ux file:

<template> <div class="item-container"> <input type="button" onclick="creatChannel" value=" create message channel "/> <input /> <input type="button" onclick="cancelChannel" Value =" close message channel "/> </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 created successfully '}); Function (event) {console.log(event.data) prompt. ShowToast ({message: 'accept message:' + event.data}); } }, routeChannel: function () { router.push({ uri: '/Test' }); }, cancelChannel: function () { channel.close(); Prompt. ShowToast ({message: 'closed message channel successfully '}); } } </script>Copy the code

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>Copy the code

More reference

Quick application document reference:

Developer.huawei.com/consumer/cn…

The original link: developer.huawei.com/consumer/cn…

Original author: Mayism