ifream父子页面信息传递
1、父级向子级传递信息通过postMessage传递
this.$refs.SonIframe.contentWindow.postMessage(this.msg, '*')
2、父级接收子级传递信息
window.addEventListener('message', function (e) {
if ((typeof e.data) === 'string') {
alert('父级接收子级返回数据:' + e.data)
}
}, false)
3、子级向父级传递信息通过postMessage传递
window.parent.postMessage(this.msg, '*')
4、子级接收父级传递信息
window.addEventListener('message', function (e) {
if (e.data) {
alert('子级接收父级返回数据:' + e.data)
}
}, false)
父级页面代码
<template>
<div class="hello">
<h1>我是爸爸</h1>
<div style="width:400px;margin:20px auto;">
<el-input placeholder="跟儿子说句话" v-model="msg">
<el-button slot="append" @click="handleMsg">发送</el-button>
</el-input>
</div>
<div style="margin-top: 15px;">
<iframe ref="SonIframe" src="https://huangchunhongzz.gitee.io/son-ifream" id="SonIframe"></iframe>
</div>
</div>
</template>
<script>
export default {
name: 'parent',
data () {
return {
msg: ''
}
},
created () {
window.addEventListener('message', function (e) {
if ((typeof e.data) === 'string') {
alert('父级接收子级返回数据:' + e.data)
}
}, false)
},
methods: {
handleMsg () {
console.log('handleMsg -> 点击了发送按钮')
this.$refs.SonIframe.contentWindow.postMessage(this.msg, '*')
console.log('handleMsg -> this.msg', this.msg)
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
#SonIframe{
width: 600px;
height: 600px;
}
</style>
子级页面代码
<template>
<div class="hello">
<h1>我是儿子</h1>
<div style="width:400px;width:400px;margin:20px auto;">
<el-input placeholder="跟爸爸说句话" v-model="msg">
<el-button slot="append" @click="handleMsg">发送</el-button>
</el-input>
</div>
</div>
</template>
<script>
export default {
name: 'son',
data () {
return {
msg: ''
}
},
created () {
window.addEventListener('message', function (e) {
if (e.data) {
alert('子级接收父级返回数据:' + e.data)
}
}, false)
},
methods: {
handleMsg () {
console.log('handleMsg -> 点击了发送')
window.parent.postMessage(this.msg, '*')
console.log('handleMsg -> this.msg', this.msg)
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
效果
demo