记录一次vue封装iframe组件后 父页面向子页面发送消息

这是一层vue对iframe的封装

<script lang="ts" setup>
import { propTypes } from '@/utils/propTypes'

defineOptions({ name: 'IFrame' })

const props = defineProps({
  src: propTypes.string.def('')
})
const loading = ref(true)
const height = ref('')
const frameRef = ref<HTMLElement | null>(null)
const init = () => {
  height.value = document.documentElement.clientHeight - 94.5 + 'px'
  loading.value = false
}
defineExpose(
  {frameRef}

)
onMounted(() => {
  setTimeout(() => {
    init()
  }, 300)
})

</script>
<template>
  <div v-loading="loading" :style="'height:' + height">
    <iframe
      ref="frameRef"
      :src="props.src"
      frameborder="no"
      scrolling="auto"
      style="width: 100%; height: 100%"
    ></iframe>
  </div>
</template>

这里用到了setup语法糖 所以需要 

defineExpose(
  {frameRef}

)导出 子组件的ref。

这是父组件 ,也是父页面

<template>
  <ContentWrap>
    <IFrame  ref="go" :src="src"   />
  </ContentWrap>
</template>
<script lang="ts" setup>
defineOptions({ name: 'GoView' })
const go = ref()
const src = 'http://127.0.0.1:3000'
onMounted(() => {

  window.addEventListener("message", (e)=>{
    if (e.data === "加载完成") {
      console.log("加载完成")
      go.value.frameRef.contentWindow.postMessage("测试","*")

    }
  })
})
</script>

首先获取父组件中IFrame的ref 在通过.value.子组件的ref名称来获取子组件的ref

go.value.frameRef

这段代码的作用是监听子组件初始化完成后发送加载完成的信息,再由于父页面向子页面发送消息

这是子组件中对父组件初始化完成后发送消息的代码

 window.parent.postMessage("加载完成","*")

注意必须是window.parent.postMessage

window.postMessage是不行的

 

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值