iframe 父子组件通信 vue3

父组件

<template>
    <div>
        <!-- 测试iframe 父子通信 -->
        <h1>父组件</h1>
        <iframe src="http://localhost:8080/#/testChild" width="80%" height="100px" ref="childIframe" id="childIframe"
            scrolling="auto">
            当前使用的浏览器不支持iframe
        </iframe>
    </div>
</template>

<script setup>
import { ref, getCurrentInstance, onMounted, onUnmounted } from "vue"
const { proxy } = getCurrentInstance();

const payEvent = (e) => {
    console.log('子传父的数据:', e.data);
}

onMounted(() => {
    // 父传子
    const oIframe = document.getElementById("childIframe").contentWindow;
    let oIframeDom = document.getElementById("childIframe");
    let data = {
        form: "parent page",
        code: 200,
        data: "1",
        type: "view"
    };
    oIframeDom.onload = () => {
        oIframe.postMessage(data, "*");
    };


    // 子传父-父接收
    window.addEventListener('message', payEvent)
})
onUnmounted(() => {
    // 父移除监听函数
    window.removeEventListener('message', payEvent)
})
</script>

子组件

<template>
    <div>
        <!-- 测试iframe 父子通信 -->
        iframe 子组件
    </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, onMounted, onUpdated, watch, computed } from "vue"
onMounted(() => {
    // console.log('子组件 mounted');
    //子传父
    let data = {
        judge: false,
    }
    window.parent.postMessage(data, '*')


    //父传子-子接收
    window.onload = () => {
        window.addEventListener('message', (event) => {
            console.log('监听父页面向子页面的传参', event.data)
        })
    }
})



</script>
<script>
</script>

路由:

  {
    path: "/testChild",
    name: "testChild",
    component: () => import("@/views/components/testChild.vue"),
    meta: {
      title: "testChild",
    },
  },
  {
    path: "/testParent",
    name: "testParent",
    component: () => import("@/views/components/testParent.vue"),
    meta: {
      title: "testParent",
    },
  },

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值