ifream parent-child page information transfer
1. The parent transmits information to the child through postMessage
this.$refs.SonIframe.contentWindow.postMessage(this.msg, '*')
2. The parent receives information from the child
window.addEventListener('message', function (e) {
if ((typeof e.data) === 'string') {
alert('父级接收子级返回数据:' + e.data)
}
}, false)
3. The child transmits information to the parent through postMessage
window.parent.postMessage(this.msg, '*')
4. The child receives the information transmitted by the parent
window.addEventListener('message', function (e) {
if (e.data) {
alert('子级接收父级返回数据:' + e.data)
}
}, false)
Parent page code
<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>
Child page code
<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>
effect
demo