1. Vue文件嵌入Html页面
-
在Public目录下放置自己的html文件
-
通过iframe嵌入上面的html文件
<template>
<div class="wrap">
<iframe
ref="iframe"
:src="htmlSrc"
width="100%"
style="height: calc(100vh)"
frameborder="0">
</iframe>
</div>
</template>
<script>
export default {
name: "index",
data() {
return {
htmlSrc:'/303/303package/index.html' // html文件所在位置
};
},
}
</script>
<style scoped lang="scss">
.wrap{
width: 100%;
min-height: calc(100vh - 84px);
}
</style>
2. 实现通信
Vue文件
<template>
<div class="wrap">
<iframe
ref="iframe"
:src="htmlSrc"
width="100%"
style="height: calc(100vh)"
frameborder="0">
</iframe>
</div>
</template>
<script>
import {getData} from "@/api/kanban/main";
export default {
name: "index",
data() {
return {
htmlSrc:'/303/303main/index.html'
};
},
methods: {
getData() {
getData().then((res) => {
this.$refs.iframe.contentWindow.postMessage(res, "*") // 将数据响应给html页面
}).catch((err) => {
console.log(err)
})
}
},
mounted() {
// 等待iframe加载完成
this.$refs.iframe.addEventListener('load', () => {
this.getData(); // 获取后端数据
});
}
}
</script>
<style scoped lang="scss">
.wrap{
width: 100%;
min-height: calc(100vh - 84px);
}
</style>
html
文件添加script
脚本获取vue
文件传递来的数据
<script>
window.addEventListener("message", function(event) {
const data = event.data;
console.log('data', data);// {plcName: '投料机#1', weight: 0.13, isNormal: true}
document.getElementById("content").innerText = JSON.stringify(data);
});
</script>
<div id="content"></div>
上面的div
内渲染的数据如下:
3. html数据传递给js文件
html文件,添加
script
脚本将vue
文件传递来的数据再传递给js文件(用于绘制echarts图表)
<!-- 引入js文件 -->
<script type="text/javascript" src="js/draw.js"></script>
<script>
window.addEventListener("message", function(event) {
const data = event.data;
console.log('data', data)
window.renderChart(data) // html文件发送数据给js文件
});
</script>
js文件
let tlData = {}
window.renderChart = function (data) {
tlData = data
console.log('tlData', tlData)
}