关于appgallery-connect:教你如何实现页面间的数据通信

场景形容
某些状况下,开发者可能须要实现页面间的消息传递来获取数据,例如A页面跳转至B页面后,B页面发送音讯给A页面,A页面可能接管到。此时能够通过音讯通道的机制来实现页面间的互相通信。

实现思路
页面messageChannel创立了音讯通道,并接管音讯。跳转到页面test,在页面test通过音讯通道发送音讯。页面messageChannel收到音讯后通过toast展现进去。

解决办法
页面messageChannel.ux文件:

<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文件:

<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/…

原文链接:https://developer.huawei.com/…
原作者:Mayism

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理