The vue project uses iframe parent-child pages to pass values.
1. The vue project calls the method in the iframe subpage.
1. Parent page
The key to calling the subpage method is to obtain the attributes iframe
of the element objectcontentWindow
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. Subpage
<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>
2. In the iframe page, call the method in the parent page that references it.
1. Parent page
The parent page only needs to add events 监听器
, and execution in the callback requires executing methods or using parameters.
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. Subpage
window.parent.postMessage
Communication implemented by subpages through methods
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');
}