- 新建父组件Main.vue
<script setup lang="ts">
import { onMounted, ref} from "vue";
const iframeRef = ref<HTMLIFrameElement | null>(null)
onMounted(() => {
// 监听-- 接收iframe发送的信息
window.addEventListener('message', (event) => {
// 检查发送的源是否是http://localhost:5173
if(event.origin !== 'http://localhost:5173'){
return
}
console.log('Main:', event)
console.log('main:', event.data)
// 先收到-- 子组件window.addEventListener监听完毕--->在开始发送给iframe信息
iframeRef.value?.contentWindow?.postMessage('发送到iframe的信息:ABC','http://localhost:5173/#/iframes')
},false)
})
</script>
<template>
<div class="main-box">
<div class="header-box">
头
</div>
<div class="content-box">
Iframe:
<iframe ref="iframeRef" :src="'http://localhost:5173/#/iframes'" width="100%" height="300"></iframe>
</div>
</div>
</template>
<style scoped>
main-box {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
}
.header-box {
width: 100%;
height: 50px;
background-color: #888888;
}
.content-box {
width: 100%;
flex: 1;
padding: 20px;
display: flex;
flex-direction: column;
box-sizing: border-box;
}
</style>
- 新建 iframesVue.vue
<script setup lang="ts">
//iframe接收消息
import {onMounted} from "vue";
onMounted(() => {
// 判断当前是否在iframe中
if(window.self !== window.top) {
console.log('iframes组件在iframe中')
} else {
console.log('iframes组件不在iframe中')
}
// 发信息给父页面
window.parent.postMessage('iframes发给main的信息:def','http://localhost:5173/#/main ')
// 监听-- 接收父页面发送的信息
window.addEventListener('message', (event) => {
// 检查发送的源是否是http://localhost:5173
if(event.origin !== 'http://localhost:5173'){
return
}
console.log('iframe:', event)
console.log('iframe:', event.data)
})
})
</script>
<template>
<div>
iframes组件----
</div>
</template>
<style scoped lang="scss">
</style>
-
结果