iframe,结合window.postMessage,实现通信

这是另一种通讯方式:https://baijiahao.baidu.com/s?id=1606945663099800547&wfr=spider&for=pc
我们用的是H5新增的

父页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<button id="btn">toSon</button>
<iframe  src="iframe.html" frameborder="0" name="son"></iframe>
<body>
    <script src="../jquery-2.1.3.js"></script>
    <script>
        $(function(){
            window.addEventListener('message',function(e){
                console.log(e);
            })
            $('#btn').on('click',function(){
                window.son.postMessage('fromFather',"*");
            })

        })
    </script>
</body>
</html>

iframe内嵌页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <button id="btn">toFather</button>
    <script src="../jquery-2.1.3.js"></script>
    <script>
        $(function(){
            $('#btn').on('click',function(){
                window.top.postMessage('hi','*');
            })
            window.addEventListener('message',function(e){
                if(e.origin!=='http://localhost'){
                    console.log("x")
                    return;
                }
                //父页面点击按钮,执行子页面的方法
                console.log(e);
            })
        })
    </script>
</body>
</html>

由于实在vue-cli项目中使用的,内嵌页面和触发条件不再一个页面中,所以需要通过,创建一个空的 Vue 实例作为事件总线。

第一步:创建空实例,并注册到根实例里

let Hub = new Vue(); //创建事件中心
new Vue({
  router,
  store,
  render: h => h(App),
  data:{
    Hub:Hub 
  }
}).$mount('#app')

第二步:Hub触发事件

this.$root.Hub.$emit('wangChange',menuId); //Hub触发事件

第三步:Hub监听事件

 this.$root.Hub.$on('wangChange', (res) => { //Hub接收事件
  })
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容