1、主应用通过在iframe的onload事件中,使用postMessage向子应用进行数据交互
2、子应用在mounted阶段通过监听onmessage事件进行接收事件
主应用
<template>
<div v-tip="loading" :style="'height:' + (isQiankun ? qiankunHeight : height)">
<iframe
ref="iframe"
:src="src"
frameborder="no"
style="width: 100%;height: 100%"
scrolling="auto"
@load="loaded"
/>
</div>
</template>
<script>
// import Cookies from 'js-cookie'
export default {
props: {
src: {
type: String,
required: true
}
},
data() {
return {
height: document.documentElement.clientHeight - 90 + 'px;',
qiankunHeight: document.documentElement.clientHeight - 114 + 'px;',
loading: 'loading'
}
},
computed: {
isQiankun() {
return this.$root.isQiankun
}
},
mounted() {
this.loading = 'loading'
// setTimeout(() => {
// this.loading = false
// // console.log(this.$refs.iframe.contentWindow.aaa = 'hzh')
// }, 230)
const that = this
window.onresize = function temp() {
that.height = document.documentElement.clientHeight - 90 + 'px;'
}
},
activated() {
// setTimeout(() => {
// this.loading = false
// }, 230)
this.loading = 'loading'
const that = this
window.onresize = function temp() {
that.height = document.documentElement.clientHeight - 90 + 'px;'
}
},
methods: {
// 向子应用下发数据
loaded() {
const iframe = this.$refs.iframe.contentWindow
iframe.postMessage(
{
type: 'ytzg',
isShowMenu: false
},
'*'
)
this.loading = false
}
}
}
</script>
子应用
mounted(){
window.addEventListener('message',this.handleMessage)
this.$on('hook:beforeDestory',()=>{
window.removeEventListener('message',this.handleMessage)
})
}
methods:{
handleMessage(event){
conosle.log(event.data)
const {data} = event
if(data.type === 'ytzg'){
this.devEnv = false
}
}
}
如果子应用也需要向主应用进行通讯
window.parent.postMessage({type:'parent'}, '*');
主应用进行接收的方式与子应用接收的方式相同
mounted(){
window.addEventListener('message',this.handleMessage)
this.$on('hook:beforeDestory',()=>{
window.removeEventListener('message',this.handleMessage)
})
}
methods:{
handleMessage(event){
conosle.log(event.data)
const {data} = event
if(data.type === 'parent'){
conosle.log('从子应用的传递的值')
}
}
}