方法一 vue
父传子
<iframe
class="compare-item"
title="对比一"
id="iframe1"
ref="iframe1"
:src="iframItem1"
:key="iframItem1"
@load="iframeOnload('iframe1')"
></iframe>
let t = new Date().getTime();
this.iframItem1 = arr[0]+ "&t="+t;
this.iframItem2 = arr[1]+ "&t="+t;
iframeOnload(id) {
let iframe = this.$refs[id];
let obj = { onlineType: "single",isTitle: true};
iframe.contentWindow.postMessage(obj, "*");
},
子级
mounted(){
//怎样监听iframe传过来的信息
window.addEventListener("message", this.handleMessage);
},
handleMessage(msg){
if(!!msg.data.onlineType){
this.onlineType = msg.data.onlineType
if(!!msg.data.isTitle){
this.onlineTitle = msg.data.isTitle
}
}
},
unMounted(){
window.removeEventListener("message", this.handleMessage)
}
子传父
子级
// iframe 传给父级用 年鉴和年鉴对比用
window.parent && window.parent.postMessage({'isFull':true},'*')
//父 iframe
window.addEventListener('message', (e) => {
console.log(e.data.isFull);
});