vue项目使用 iframe 父子页面传值。
一、vue项目调用iframe子页面中的方法。
1. 父页面
调用子页面方法的关键在于获取到iframe
元素对象后的contentWindow
属性
this.$refs.iframeName.contentWindow.FunctionName()
<template>
<div class="pjpccx">
<h1 class="title_color">{
{
title }}</h1>
<button @click="reportPrint">点击调用iframe中的方法</button>
<iframe ref="iframe" src="/static/zkjs/base.html" width="100%" height="100%" style="border: none;" class="iframe" frameborder="0" scrolling="yes" name="iframe" seamless>您的浏览器版本过低,无法显示报表内容!建议升级浏览器或更换浏览器!</iframe>
</div>
</template>
export default {
methods: {
reportPrint() {
// 父页面调用子页面方法
this.$refs.iframe.contentWindow.openThePage()
// 父页面向子页面传值
this.$refs.iframe.contentWindow.postMessage(param)
}
}
}
2. 子页面
<script type="text/javascript">
// 打开某一页
function openThePage() {
new Device().startFun()
}
// 子页面接受父页面的传值
window.addEventListener('message', messageEvent => {
if (messageEvent.source != window.parent.window.parent) return;
paramData = messageEvent.data
changeUrl(paramData)
})
</script>
二、在iframe页面中,调用引用它的父页面中的方法。
1. 父页面
父页面则只需要添加事件监听器
,在回调中执行需要执行方法或者使用参数。
mounted() {
let _this = this
// 父页面接受子页面的传值
window.addEventListener('message', function (e) {
console.log(e) //{data:'params'}
console.log(e.data.Name||e.data.result.Name)
_this.form.name = e.data.Name||e.data.result.Name
})
},
2. 子页面
子页面通过window.parent.postMessage
方法实现的通信
function setCertificateData(result) {
// 子页面传值给父页面
window.parent.postMessage({
data: "params",
}, '*');
// 子页面传值给指定父页面
window.parent.postMessage(result.Certificate, 'http://localhost:8080/#/formVue');
window.parent.postMessage({
result: result.Certificate}, 'http://localhost:8080/#/formVue');
}