Vue iframe父子页面通讯及事件触发过程
更新时间:2026年06月30日 09:19:14 作者:深海蓝山的博客
这段文章主要介绍了Vue框架下利用iframe实现父子页面通讯的方法,重点讲解了使用window.postMessage API进行事件触发与监听,文章通过具体代码示例详细展示了主页面与iframe页面间如何进行有效通讯
Vue iframe父子页面通讯及事件触发
通过window.postMessage API 实现父页面与iframe页面的事件通讯
通过addEventListener监听message,使用window.postMessage实现跨iframe的页面事件通信,子页面通过iframe 引入,
代码如下:
主页面代码
<template>
<div><el-button type="primary" @click="handleToIframe">主页面向iframe发送信息</el-button></div>
<iframe ref="fIframe" class="iframeClass" src="http://localhost:8080/iframeCall"></iframe>
</div>
</template>
<script>
mounted() {
// 监听子页面想父页面的传参
window.addEventListener('message', function(event) {
//此处执行事件
console.log('监听子页面向父页面的传参', event.data);
});
},
methods: {
// 父页面处发向子页面传参
handleToIframe() {
let data = {
from: 'parent page',
code: 200,
data: '来自父页面的数据!!!'
};
this.$refs.fIframe.contentWindow.postMessage(data, '*');
}
}
};
</script>
<style scoped>
.iframeClass {
width: 300px;
height: 100px;
border: 1px solid red;
}
</style>
子页面代码示例
<template>
<div>
<el-button type="success" size="small" @click="sonClick">子页面触发</el-button>
<div>这是通过iframe引的子页面</div>
</div>
</template>
<script>
export default {
mounted() {
// 监听父页面向子页面的传参
window.addEventListener('message', e => {
console.log('父页面传输过来参数', e.data);
});
},
methods: {
// 子页面处发向父页面传参
sonClick() {
let data = {
from: 'iframe child page',
code: 200,
data: '子页面主动触发通讯'
};
window.parent.postMessage(data, '*');
}
}
};
</script>
效果示例

总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
elementUI中的$confirm调换两个按钮位置的实例代码
这篇文章主要介绍了elementUI中的$confirm调换两个按钮位置的实例代码,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧2024-03-03
Vue+better-scroll 实现通讯录字母索引的示例代码
通讯录字母索引是常用的一种功能,本文主要介绍了Vue+better-scroll 实现通讯录字母索引,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2022-06-06


最新评论