vue中iframe的使用(1)

文章展示了在Vue项目中如何通过iframe进行跨域通信,主要方法包括使用`postMessage`向iframe传递数据,并在iframe内部通过监听`message`事件来接收数据。示例代码详细说明了在父组件中设置iframe以及在子组件中接收数据的过程。
摘要由CSDN通过智能技术生成

1. 记录vue中使用iframe,直接上代码

父元素给iframe传值的方法

<template>
  <div>
      <iframe ref="iframeClass" src="https://xxxxxx/iframe-online-service" width="1000" height="700" frameborder="0"></iframe>
<button @click="testFun">测试</button>
  </div>
</template>

<script>
export default {
  mounted(){
    // 方法一
        const iFrame = that.$refs['iframeClass']
        iFrame.onload = function () {
          let data = {
            agentId: 'zzzz'
          }
          iFrame.contentWindow.postMessage(data, '*')
        }
  },
  methods: {
    // 方法二
    testFun(){
        const iFrame = that.$refs['iframeClass']
        let data = {
            agentId: 'zzzz'
          }
          iFrame.contentWindow.postMessage(data, '*')
        }
    }
}
</script>
<style lang="less" scoped>

</style>

iframe接收父元素传的值

<template>
  <div> iframe子元素 </div>
</template>

<script>
export default {
  mounted(){
      window.addEventListener('message', (e) => {
          const data = e.data
          console.log(e)
      })
  }
}
</script>
<style lang="less" scoped>

</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值