vue进阶 Iframe基础

本文详细介绍了如何在Vue项目中使用Iframe组件,并探讨了跨域限制下Iframe与父页面之间的通信方法,包括如何从Vue向Iframe传值及从Iframe向Vue传值。

目录

Iframe

获取iframe里面的内容

Iframe 注意事项

vue页面使用iframe

iframe  与 vue 直接的交互

vue 向 iframe  传值

iframe 向 vue 传值


Iframe

Iframe 在同域时能自由操作iframe和父框架的内容(DOM),在跨域时可以实现页面跳转。

获取iframe里面的内容

iframe.contentWindow, 获取iframe的window对象
iframe.contentDocument, 获取iframe的document对象

Iframe 注意事项

1 使用 iframe 后,window.location.href 将拿不到导航栏信息,也无法监听和计算属性

2 可以使用  parent.location.href  或者  document.referrer 拿到最外层导航栏信息,但是无法进行监听和计算属性

vue页面使用iframe

template  引入

  <Iframe :src="iframeSrc" width="100%"  height="100%"  ref="iframe" />

iframe 路径  建议写在 mounted 中,可以设置路径和参数

 onMounted(() => {
      iframeSrc.value = `/sheet/send? 
      full=true&id=${uuid}&instance_plan_id=${instance_plan_id}`;
    });

iframe  与 vue 直接的交互

vue 向 iframe  传值

vue  页面

 const mapFrame = this.$refs['iframe'];
 const iframeWin = mapFrame.contentWindow;
 iframeWin.postMessage(
   {
     value: 'backSuccess',
     id: 'vue',
     success: true
    },
   '*'
 );

iframe 接受 vue 的值  建议写在 mounted  和 created 中

window.addEventListener('message',e=>{
  console.log(e,'vue 传递过来的数据')  
})

iframe 向 vue 传值

iframe 页面

window.parent.postMessage(obj, '*');
//如果js外面还有一层js,
window.parent.window.parent.postMessage(obj, '*');

vue 监听 iframe 传过来的值

 mounted() {
    //   获取并监听iframe传递来的数据
    let that = this;
    window.addEventListener('message', function (e) {
      var res = e.data;
      console.log(res, 'iframe传递过来的数据');
      })
 }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值