这是另一种通讯方式: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接收事件
})