ifream親子ページ情報転送

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: {
    
    
    /**
     * @description:发送信息
     * @param {*}
     * @return {*}
     * @author: hch
     */
    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: {
    
    
    /**
     * @description: 发送信息
     * @param {*}
     * @return {*}
     * @author: hch
     */
    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>

効果

デモ

ここに画像の説明を挿入

ここに画像の説明を挿入

おすすめ

転載: blog.csdn.net/qq_39367226/article/details/109491572