关于Vue项目嵌入Html页面并且实现通信

1. Vue文件嵌入Html页面

  1. 在Public目录下放置自己的html文件
    在这里插入图片描述

  2. 通过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)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值