方式1 : window.postMessage()
语法:
发送端:targetWindow.postMessage(message, targetOrigin, [transfer])
备注:targetWindow 是接收消息的窗口的引用
1.1 父端:window.frames +索引值 : 如 window.frames[0]
1.2 子端:window.parent
message 是要具体传的值:例如 { width: 10 }
targetOrigin 是指定目标窗口的来源,可以是字符串“*”或URI, *表示任何目标窗口都可接收
transfer是可选参数
接收端:window.addEventListener("message", receiveMessage, false);
备注:“message” 是固定的属性,是指要监听消息类型
receiveMessage 是方法名,也就是监听到消息后要处理的方法
例子:
父parent.html :
<iframe id="iframeId" name="iframeId" width="100%" src="http://localhost:8080/" frameborder="0" ></iframe>
<span @click="test" id="test">测试</span>
mounted () { // 在页面渲染完后进行监听
window.addEventListener('message',function(e){
console.log(e)
document.getElementById('iframeId').style.width = e.data.width
},false);
},
beforeDestroy () { // 在页面销毁前去掉监听,防止内存泄露
window.removeEventListener('message')
},
methods: {
test(){
window.frames[0].postMessage({ hi : 10 },'*') // 给子页面发送信息
},
}
子child.html :
<span @click="test" id="test">测试</span>
mounted () { // 监听父页面数据
window.addEventListener('message', function(e){
console.log(e)
})
},
methods: {
test(){
window.parent.postMessage({ width: 100 },'*'); // 给父页面发送信息
},
}
方式2: 监听route变化
父parent.html :通过改变iframe路径,把需要的参数放在url中,再加个时间戳,确保每次点击时url都是改变的
<iframe id="iframeId" name="iframeId" width="100%" src="http://localhost:8080/" frameborder="0" ></iframe>
<a-button type="primary" @click="print">打印</a-button>
methods: {
print () {
let random = new Date()
random = random.getTime() // 时间戳
document.getElementById('iframeId').src="http://localhost:8080/#/print?btn_type=print&random="+random
},
}
子child.html : 通过监听路由的改变,来动态调用子页面中的方法
watch: {
$route: { // 监听路由变化
async handler () {
let que = this.$route.query
await this.initD() // 初始化数据
if (que.btn_type == 'print') { // 点击了打印按钮
this.$nextTick(() => {
this.temPrint(que.btn_type) // 调用打印
})
}
},
//immediate: true // 首次进来看需求是否需要监听
},
},