您现在的位置是:首页 >其他 >vue中嵌入iframe网站首页其他
vue中嵌入iframe
简介vue中嵌入iframe
在vue中嵌入一个别的网址或者其他非vue实现的本地html,可以采用iframe标签的方式。两者交互采用postMessage方法,可以直接利用document.getElementById的方式获取iframe对象,也可以采用vue中的ref的方式获取。效果如下。
1、vue文件代码
<template>
<div class="maindiv">
<el-row >
<el-button type="primary" size="default" @click="sendToIframe">发送消息给iframe</el-button>
<el-button type="primary" size="default" @click="sendToIframe2">发送消息给iframe2</el-button>
</el-row>
<el-row >
<iframe id="iframe1" ref="myIframe" src="@/../public/iframe1.html" frameborder="0"></iframe>
</el-row>
</div>
</template>
<script setup>
import { ref, reactive, onMounted,shallowRef } from "vue";
const myIframe = ref(null);
onMounted(() => {
});
function sendToIframe()
{
let msgobj = {
type : "test",
data : "hello"
}
let iframe = document.getElementById("iframe1");
iframe.contentWindow.postMessage(JSON.stringify(msgobj), "*");
}
function sendToIframe2()
{
console.log(myIframe.value);
let msgobj = {
type : "func",
data : "testFunc"
}
myIframe.value.contentWindow.postMessage(JSON.stringify(msgobj), "*");
}
</script>
<style>
.maindiv {
width: 100%;
height: 100%;
}
</style>
2、iframe1.html文件
<!DOCTYPE html>
<html lang="en">
<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>
</head>
<body>
<button>测试</button>
</body>
<script>
window.onload = function() {
// 你的函数代码放在这里
console.log('页面已完全加载,包括所有资源');
// 例如,初始化页面元素、设置事件监听器等
};
function testFunc() {
alert('this is a test function');
}
window.addEventListener('message', function(e) {
let msgObj = JSON.parse(e.data);
if (msgObj.type === 'test') {
alert('data from domain2 ---> ' + msgObj.data);
}
else if (msgObj.type === 'func') {
//msgObj.data();
window[msgObj.data](); //函数是在全局作用域中定义的,你可以通过 window 对象来访问它。或者自己定义一个全局函数对象
}
}, false);
</script>
</html>
风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。