- 创建一个名为 PostMessageIframe 的新组件。
<template>
<iframe ref="iframe" :src="src" @load="handleLoad"></iframe>
</template>
<script>
export default {
props: {
src: {
type: String,
required: true
}
},
methods: {
handleLoad() {
// 在 iframe 载入后,添加 message 事件监听器
window.addEventListener('message', this.handleMessage)
},
handleMessage(event) {
// 处理收到的消息
const message = event.data
console.log('Received message:', message);
// 执行你想要的操作,例如更新组件的数据或回调函数
},
sendMessage(message) {
// 发送消息到 iframe
const iframeWindow = this.$refs.iframe.contentWindow
iframeWindow.postMessage(message, this.src)
}
},
beforeDestroy() {
// 在组件销毁前移除事件监听器
window.removeEventListener('message', this.handleMessage)
}
}
</script>
- 在需要使用的地方引入并使用 PostMessageIframe 组件。
<template>
<div>
<button @click="sendPostMessage">发送消息到 iframe</button>
<PostMessageIframe :src="iframeSrc" ref="postMessageIframe" />
</div>
</template>
<script>
import PostMessageIframe from '@/components/PostMessageIframe.vue'
export default {
components: {
PostMessageIframe
},
data() {
return {
iframeSrc: 'https://example.com/iframe-src' // 替换为你的 iframe 页面地址
}
},
methods: {
sendPostMessage() {
const postMessageIframe = this.$refs.postMessageIframe
postMessageIframe.sendMessage('Hello, iframe!')
}
}
}
</script>
在这个示例中,我们通过引用和使用 PostMessageIframe 组件来发送和接收 postMessage。在按钮的点击事件处理函数 sendPostMessage 中,我们通过 $refs 获取到 PostMessageIframe 组件的实例,并调用其 sendMessage 方法向 iframe 发送消息。
当 iframe 载入完成时,通过监听 message 事件来接收从 iframe 发送过来的消息,并在 handleMessage 方法中进行相应的处理。
请将 iframeSrc 替换为你实际使用的 iframe 页面地址。这样,你就可以使用封装的组件来进行 postMessage 通信了。