<template>
<view>
<view>
//src:页面地址
<iframe ref="iframe" id="iframe" :src="..." class="..."></iframe>
</view>
<view :dataItem="dataItem" :change:dataItem = "renderModal.dataChange"></view>
<button @click="renderModal.dataClick"></button>
</view>
<template>
<script>
export default {
components:{},
data() {
return {
dataItem:''
},
},
methods:{
receiveRenderData(e){
//接收的值
console.log(e)
}
}
}
</script>
<script module="renderModal" lang="renderjs">
export default {
data() {
return {
dom: '',
}
},
mounted() {
this.dom = document.getElementById('iframe')
// 接收iframe传过来的值
window.addEventListener('message', (e)=> {
var data = e.data;
this.emitData(data.msg)
});
},
methods: {
emitData(e) {
// 将值传到当前页面
this.$ownerInstance.callMethod('receiveRenderData',e)
},
// data的值发生改变时会触发dataChange并且将值传到iframe页面中
dataChange(e) {
param:{data:e}
this.dom.contentWindow.postMessage(param,'*')
}
// 点击按钮时将值传到iframe页面中
dataClick() {
this.dom.contentWindow.postMessage('点击了按钮','*')
}
}
}
</script>
</style>
iframe中
<!DOCTYPE html>
<html lang="en" style="height: 100%;">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js"></script>
</head>
<body style="height: 100%;margin: 0;" >
<div></div>
</body>
<script>
window.onload=()=>{
getData()
}
function getData(){
let info = {
data:'123'
}
//将值传入uniapp页面
window.parent.postMessage(info, '*');
}
window.addEventListener('message', function (e) {
//接收uniapp中传过来的值
console.log(e.data)
})
</script>
案例
注意单独的一个组件使用,不然不能接收change的变化
<template>
<view>
<view class="map">
<iframe ref="iframe" id="iframe" class="receiver-frame"
src="https://mon.yced.com.cn/disasterDevicesMap.html"
style="border: none; width: 100%; height: 100%"></iframe>
</view>
<view id="renderModal" :data="data" :change:data="renderModal.receiveInfo"></view>
</view>
</template>
<script>
export default {
props:{
features:{
type:Object,
default:()=>{
return{}
}
}
},
data() {
return {
data:null
}
},
methods: {
},
watch:{
features:{
handler(newValue){
console.log('接收features',newValue)
this.data=newValue
},
deep:true
}
},
mounted() {
},
}
</script>
<script module="renderModal" lang="renderjs">
export default {
data() {
return {
dom: '',
}
},
mounted() {
this.dom=document.getElementById('iframe');
// console.log('dom',this.dom)
// this.dom.contentWindow.postMessage({ id: "highLightDeviceById", data: 123 },
// "*")
},
methods: {
emitData(e) {
// 将值传到当前页面
// this.$ownerInstance.callMethod('receiveRenderData',e)
},
receiveInfo(newValue, oldValue, ownerInstance, instance){
if(this.dom){
console.log('接收数据了',newValue, oldValue, ownerInstance, instance);
this.dom.contentWindow.postMessage(newValue,
"*")
}
},
}
}
</script>
<style lang="scss" scoped>
</style>