iframe父页面调用子页面方法 子页面传数据到父页面

发布时间 2023-05-06 15:38:22作者: Chaplink
//父页面
<template>
    <div>
        <iframe id="PanIframe" width="100%" height="2000px" src="http://127.0.0.1:7006/formCreateDesigner"></iframe>
    </div>
</template>

<script lang="ts" setup>
import {ref} from 'vue'
const receiveMessageIframePage = (event) => {
    if (event.data.type === 'check') {
        console.log(event.data.data)
    }
}
window.addEventListener('message', receiveMessageIframePage, false)
//setTimeout替换成触发方法
setTimeout(() => {
    const iframeWindow = document.getElementById("PanIframe").contentWindow.window.methods;
    iframeWindow.sendData();
}, 5000)
</script>

<style lang="scss" scoped>

</style>
//子页面
window.methods = {
    sendData: () => {
        window.parent.postMessage({ type: 'check',  data:你要传的数据, '*')
    }
}