vue3 与 html文件 通讯
postMessage方法传递
postMessage方法是HTML5中提供的一种跨文档通信的方式,可以在不同的窗口或者iframe之间传递数据。
<template>
<button @click="vueSendMsg">vue向iframe传递信息</button>
<iframe
:src="iframeUrl"
frameborder="0"
ref="iframeDom"
style="width: 100vw; height: 100vh"
></iframe>
</template>
<script lang="ts">
import { ref,reactive, defineComponent, onMounted, computed } from "vue";
export default defineComponent({
name: "IframeComponent",
setup(props) {
const iframeUrl = computed(() => {
const url = "/public/static/index.html";
return url;
});
const data = reactive({
des: "传递的数据"
});
const iframeDom = ref();
const vueSendMsg = () => {
const iframeWindow = iframeDom.value.contentWindow;
iframeWindow.postMessage(JSON.stringify(data), "*");
};
const receiveChild = (e) => {
if(e.data.type == "jsonData"){//
console.log(e.data.jsonData,'接收到了数据')
}
};
onMounted(() => {
// 获取子页面传输数据
window.addEventListener("message", receiveChild);
});
return {
iframeUrl,
vueSendMsg,
iframeDom
};
}
});
</script>
<style lang="scss" scoped>
.iframe-dom {
width: 100%;
height: 100%;
border: 0;
}
</style>
vue2组件
<template>
<div class="home">
<button @click="sendMsgToParent">测试给父组件发布数据</button>
<span>{{ parentData }}</span>
</div>
</template>
<script>
export default {
name: 'HomeView',
components: {
},
data () {
return {
parentData: '父组件数据',
data: {
jsonData: '测试json数据',
type: 'jsonData'
}
}
},
methods: {
handleMessageFromParent (event) {
let data = {}
console.log('收到父页面消息', event)
console.log('数据格式', typeof event.data)
if (typeof event.data === 'string') {
data = JSON.parse(event.data)
}
if (data?.type === 'initData') {
this.parentData = data?.des
}
},
sendMsgToParent () {
// 给父页面发送消息
window.parent.postMessage(
this.data,
'*'
)
}
},
mounted () {
// 监听父页面发送过来的消息
window.addEventListener('message', this.handleMessageFromParent)
}
}
</script>
html文件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>💗</title>
<style> </style>
</head>
<body>
<button id="left_test" title="测试给父组件发布数据"><i class="layui-icon layui-icon-set">测试给父组件发布数据</i></button>
<script class="iframe">
window.onload = function () {
// 接收父页面传参
window.addEventListener('message', (event) => {
let data = JSON.parse(event.data)
console.log(data)
});
};
document.getElementById("left_test").addEventListener("click", function (event) {
let data = {
jsonData: '测试json数据',
type: 'jsonData'
}
// 传参
window.parent.postMessage(data, '*')
});
</script>
</body>
</html>