vue项目中,调用iframe子网页中的方法 和在iframe子页面中调用vue父页面中的方法。

一、vue项目调用iframe子页面中的方法。
父页面代码:
faclon

<template>
  <div class="pjpccx">
    <h1 class="title_color">{{ title }}</h1>
    <button @click="reportPrint">点击调用iframe中的方法</button>
    <iframe ref="iframe" :src="urlPath" class="iframe" frameborder="0" scrolling="yes" name="iframe" seamless>您的浏览器版本过低,无法显示报表内容!建议升级浏览器或更换浏览器!</iframe>
  </div>
</template>

export default {
	methods: {
    reportPrint() {
      this.$refs.iframe.contentWindow.Print()
    }
  }
}


可以看到,调用子页面方法的关键在于获取到iframe元素对象后的contentWindow属性,所以这里使用了$refs ,如果使用dom方法获取也是可以的 。
总结一下就是 :

this.$refs.iframeName.contentWindow.FunctionName()

二、在iframe页面中,调用引用它的父页面中的方法。
父页面代码:

<body>
  <h1>我是父页面</h1>
  <iframe src="http://127.0.0.1:5050" frameborder="0" style="height: 100%;width: 100%"></iframe>
  <script>
    function fatherFunction() {
      alert('我是父页面中的方法!')
    }
    window.addEventListener('message', function(e){
            console.log(e) //{data:'params'}
            fatherFunction()
    })
  </script>
</body>

子页面代码:

<template>
  <div class="weather-app" :class="currentWeatherBG">
    <button @click="test">我是子页面按钮,点击调用父页面方法</button>
  </div>
</template>
<script>
export default {
  methods: {
      test() {
      window.parent.postMessage({
        data :"params"
      },'*');
    },
 }
}
</script>

可以看到,这里关键是子页面通过postMessage方法实现的通信,postMessage的使用方法为:

otherWindow.postMessage(message, targetOrigin, [transfer]);

message为需要传递的信息,
targetOrigin为指定哪些窗口能接收到消息事件,可以为’*’,但是这样很不安全,建议根据实际项目精确匹配。

而父页面则只需要添加事件监听器,在回调中执行需要执行方法或者使用参数。

window.addEventListener('message', function(e){
        console.log(e) //{data:'params'}
        fatherFunction()
})
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值