首页 > 移动开发 > ANDROID > 教你如何实现页面间的数据通信
某些情况下,开发者可能需要实现页面间的消息传递来获取数据,例如A页面跳转至B页面后,B页面发送消息给A页面,A页面能够接收到。此时可以通过消息通道的机制来实现页面间的相互通信。
页面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/consumer/cn/doc/development/quickApp-References/quickapp-script
原文链接: https://developer.huawei.com/consumer/cn/forum/topic/0201460275887380907?fid=0101271690375130218
原作者:Mayism
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69970551/viewspace-2779661/ ,如需转载,请注明出处,否则将追究法律责任。