window.postMessage使用
一、项目需求
比如a、b两个项目,在a项目中点击路由页面显示b项目的页面。使用iframe来显示b项目。
a点击跳转时需将b项目中需要的数据传递过去。
WebApi文档:window.postMessage - Web API | MDN
二、代码实现
a项目中需要显示b项目的页面vue文件
<template>
<div>
<iframe :src="iframeUrl" width="100%" height="800px" ref="myIframe" @load="onIframeLoad"></iframe>
</div>
</template>
<script lang="ts" setup>
import { ref, onMounted } from 'vue';
const myIframe = ref(null); // iframe 的引用
const iframeUrl = 'https://st.camel.com.cn/'; // 其他项目的 URL
const data = {
userId: 123,
userName: 'John Doe',
token: 'abc123',
};
function onIframeLoad(){
if(myIframe.value && myIframe.value.contentWindow){
myIframe.value.contentWindow.postMessage(data, '*');
}
}
</script>
b项目接收 原本我是在b项目中的vue文件中监听发送的数据但是获取不到。然后我就在router文件中,路由守卫中监听。
router.beforeEach((to, from, next) => {
// 监听父组件发送的消息
window.addEventListener('message', (event) => {
const { userId, userName, token } = event.data;
console.log('Received data from parent:', userId, userName, token);
});
});