mounted() { // 监听子页面想父页面的传参 window.addEventListener('message',function(event){ //此处执行事件 console.log('监听到子页面的传参') console.log(event.data) }) },
let data = { type:1, code:200, data:this.dictionaryInspectionId //子页面传输数据过来了 } window.parent.postMessage(data,'*')
父页面通过按钮向子页面传参,并监听子页面的传参
<template> <div> <iframe ref="fIframe" class="iframeClass" src="http://*****:8081/" frameborder="0"></iframe> <div class="btn" @click="fClick">父页面传参</div> </div></template><script> export default { mounted() { // 监听子页面想父页面的传参 window.addEventListener('message',function(event){ //此处执行事件 console.log('监听到子页面的传参') console.log(event.data) }) }, methods: { // 父页面处发向子页面传参 fClick(){ let data = { type:2, code:200, data:'父页面面传输数据过来了' } this.$refs.fIframe.contentWindow.postMessage(data,'*') }, } }</script><style > .btn{ width: 100px; height:50px; text-align: center; line-height:50px; border: 1px solid #ccc; border-radius: 12px; position:fixed;top:0;left:0; } .iframeClass{ width:100%;height:100vh; }</style>
子页面向父页面传参并监听父页面传参
<template> <div> <div class="btn1" @click="sonClick">子页面处发</div> </div></template><script> export default { mounted() { // 监听父页面向子页面的传参 window.addEventListener('message', (e) => { console.log('父页面传输过来参数') console.log(e.data) }); }, methods: { // 子页面处发向父页面传参 sonClick(){ let data = { type:1, code:200, data:'子页面传输数据过来了' } window.parent.postMessage(data,'*'); }, } }</script><style > .btn1{ width: 100px; height:50px; text-align: center; line-height:50px; border: 1px solid #ccc; border-radius: 12px; position:fixed;top:0;right:0; z-index:999999; } .iframeClass{ width:100%;height:100vh;border:1px solid red; }</style>