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

<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()
})

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐