vue3中使用iframe嵌入vue2页面

vue3中使用iframe嵌入vue2页面或vue页面和iframe页面的相互传参问题

记录一个开发过程中遇到的问题,Vue3项目中嵌入了一个iframe,iframe里面的是一个vue2项目的页面,是项目赶工计较着急,来不及把vue2集成到vue3中,这时候想到用Vue3和Vue2之间来回互调传参,下面提供解决思路。

Vue3 父组件

<template>
  <div class="content">
    <iframe
      id="unityiframe"
      ref="iframeRef"
      name="iframeContain"
      seamless
      scrolling="yes"
      :src="srcUrl"
      style="width: 100%; height: 70vh; border: 0"
    >
    </iframe>
  </div>
</template>
<script>
import { reactive, toRefs,  onMounted, ref,watch, nextTick,
         getCurrentInstance,} from "vue";
export default {
setup() {
    //接受子组件穿过来的值
    function handleMessage(event) {
      console.log("子页面传过值event", event.data);
      var datalist = event.data;
      if (datalist) {
        sendMessage();
      }
    }
    // 调用vue中getCurrentInstance方法(此参考V2和V3中this.$refs区别)
    const currentInstance = getCurrentInstance();
    function sendMessage() {
      //  currentInstance.ctx.$refs是vue3的写法。vue2中是 this.$refs
      if (currentInstance.ctx.$refs.iframeRef) {
        //判断他不为空,可根据自己的页面判断
        currentInstance.ctx.$refs.iframeRef.contentWindow.postMessage(
          // 向子页面iframe传递
          "aaa", //传递的参数
          "http://10.1.0.238:88/#/workspace/formsPanel" //iframe的页面地址
        );
      }
    }
    nextTick(() => {
      window.addEventListener("message", handleMessage);
    });
    return{
    handleMessage,
    currentInstance,
    sendMessage
    }
    }}
   </script>

Vue2 子组件(1)

  mounted() {
    //给父页面发送消息
    window.parent.postMessage(
      "111",
      "http://10.1.0.238:8080/#/application/function"
    );
    //监听父页面发送过来的消息
    window.addEventListener("message", this.handleMessageFromParent);
  },
  methods: {
    // 接收父页面发送的消息
    handleMessageFromParent(event) {
      console.log("父页面传过值event", event.data);
    },

Vue2 子组件(2)


 mounted() {
    //给父页面发送消息
    window.parent.postMessage(
      "111",
      "http://10.1.0.238:8080/#/application/function"
    );

   window.addEventListener("message", (e) => {
       //接收父页面发送的消息
        console.log("e",e)
  })
  },
  methods: {
   
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值