Vue2项目开发过程中遇到一个需求在网上找了很多插件,匹配度不高。后找到当Vue3的插件比较满足当前的需求,由于考虑到项目是基于Vue2,插件的源码是Vue3的。求助大佬,给出建议使用iframe尝试解决。以下是我整理的使用方法,可参考:
iframe的详细用法建议查看文档
一、将插件的源码下载本地运行调试
二、在需要配置插件的项目中 创建一个vue文件
<template>
<div id="box" v-loading="loading" style="width: 100%; height: 100%">
<iframe v-if="ibShow" id="my-iframe" :src="iframeSrc" frameborder="0" style="width: 100%; height: 100%" />
</div>
</template>
<script>
export default {
name: '',
components: {},
data() {
return {
iframeSrc :''
}
},
created() {
this.iframeSrc = 'iframe.src' // 需要配置的插件访问地址
},
mounted() {
this.loading = true
const iframe = document.getElementById('my-iframe')
iframe.onload = () => {
this.loading = false
const iframeWindow = iframe.contentWindow
let message = '传输的消息'
let targetOrigin = 'iframe.src'
iframeWindow.postMessage(message, targetOrigin) // 向嵌入的iframe Vue3插件发送消息
}
// 监听 iframe 发送的 message 事件
window.addEventListener('message', this.fniInitMessage)
},
destroyed() {
// 移出监听
window.removeEventListener('message', this.fniInitMessage)'
},
methods:{
fniInitMessage(event){ console.log(event) }
}
}
</script>
三、在Vue3插件项目中配置监听接收来自于Vue2项目传输的消息,以及向Vue2项目发送消息
<script>
// 假设我们有一些需要发送到父页面的信息
function sendMessageToParent() {
parent.postMessage({ greeting: "Hello, I am the iframe!" }, "http://example.com");
}
// 当页面加载完成后,发送消息
window.onload = function () {
sendMessageToParent();
};
// 监听来自父页面的消息
window.addEventListener("message", function (event) {
if (event.origin !== "http://example.com") {
// 反向验证消息源的可信度
return;
}
if (event.data && event.data.response) {
console.log("Message received from parent:", event.data);
// 可根据消息实现特定的逻辑
}
});
</script>
以上便完成了Vue2项目中使用Vue3插件的相互通信问题。若需部署上线,可选择打包配置静态资源或是部署nginx