【Vue3】 给iframe传数据

当在Vue 3框架中需要与<iframe>标签进行数据传递时,可以使用postMessage方法

传输数据

选项式:

<template>
  <div>
    <iframe ref="myIframe" :src="iframeSrc"></iframe>
    <button @click="sendMessageToIframe">向 iframe 发送消息</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      iframeSrc: "iframe加载的网页地址"
    };
  },
  methods: {
    sendMessageToIframe() {
      const iframe = this.$refs.myIframe;

      // 要发送的数据
      const dataToSend = {
        message: "选项式API传输数据的方式"
      };

      // 使用 postMessage 发送数据给 iframe
      iframe.contentWindow.postMessage(dataToSend, "*");
    }
  }
};
</script>

组合式:

<template>
  <div>
    <iframe ref="myIframe" :src="iframeSrc"></iframe>
    <button @click="sendMessageToIframe">向 iframe 发送消息</button>
  </div>
</template>

<script setup>
import { ref } from 'vue';

const iframeSrc = ref("iframe加载的网页地址");
const myIframe = ref(null);

const sendMessageToIframe = () => {
  const iframe = myIframe.value;

  // 要发送的数据
  const dataToSend = {
    message: "组合式API传输数据的方式"
  };

  // 使用 postMessage 发送数据给 iframe
  iframe.contentWindow.postMessage(dataToSend, "*");
};

return {
  iframeSrc,
  myIframe,
  sendMessageToIframe
};
</script>

接收数据

 window.addEventListener("message", function(event) {
   // 确保来源是可信任的域
   if (event.origin !== "你的网址") {
     return;
   }

   // 获取从 Vue 组件发送过来的数据
   var receivedData = event.data;

   // 在这里处理接收到的数据
   console.log(receivedData.message); // 输出传输过来的数据
 });
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值