父頁面
父頁面運行在8080端口,通過iframe標簽引用子頁面,通過postMessage發送消息給iframe中的子頁面。
<template>
<div class="hello">
<iframe id="iframe" src="http://10.10.30.5:8081" style="display:block;" width="50%" height="100%"></iframe>
<button @click="action()">發消息</button>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
msg: 'parent'
}
},
methods:{
action(){
this.show = true
var iframe = document.getElementById('iframe');
var data = {
src:"parent",
msg:"hello",
serNo:Math.floor(Math.random() * (1000 - 1)) + 1
};
iframe.contentWindow.postMessage(JSON.stringify(data), '*');
}
},
mounted() {
window.addEventListener('message', function(e) {
console.log('parent ---> ' + e.data);
}, false);
},
created() {
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
子頁面
父頁面運行在8081端口,通過監聽message消息變化接收父頁面中傳遞過來的參數,通過window.parent.postMessage發送消息給父頁面。
<template>
<div class="hello">
<button @click="sendMessageToParent()">發送消息給父組件</button>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
msg: 'sunyiwei'
}
},
methods:{
sendMessageToParent(){
let data = {
src:"child",
msg:"hello",
serNo:Math.floor(Math.random() * (1000 - 1)) + 1
}
window.parent.postMessage(JSON.stringify(data),'*');
}
},
created() {
},
mounted() {
window.addEventListener('message', function(e) {
if(e.data == undefined){
return
}
if (e.data) {
console.log('child ---> ' + e.data)
}
var data = JSON.parse(e.data);
}, false);
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.hello{
width: 100%;
height: 500px;
background-color: #fff;
}
</style>