当在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); // 输出传输过来的数据
});