教你如何實現頁面間的數據通信


場景描述

某些情況下,開發者可能需要實現頁面間的消息傳遞來獲取數據,例如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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM