最近在做vue的项目时候,需要引入本地html页面,中间遇到了很多问题,费时又费力,因此记录下来,以备不时之需,也给大家提供点资料。
ifram标签直接引用对应的html,代码如下:<iframe src="/static/b.html" width="100%" height="100%" ref="iframeDom">iframe>
src路径的问题 + js动画加载的问题: (非常重要)
html页面放在public文件夹下的static内,如果没有static文件夹,就自己新建一个。src直接网址写全就行,如:‘https://www.baidu.com’。html中需要引入外部的css或者js,这些js和css也必须在public文件夹下 。如图:
我这里是新建了一个js_css文件夹,然后把html中所用的文件放在了里面,在html中引用这些js或者css文件的话如下:
<link rel="stylesheet" type="text/css" href="js_css/pviz-core.css">
<script src="js_css/pviz-bundle.min.js">script>
vue中的写法
注意:this.$refs.iframeDom.contentWindow 中的iframeDom一定是iframe标签中的ref属性所对应的值。
<template>
<div class="main">
<button @click="vueSendMsg">vue向iframe传递信息button>
<iframe src="/static/b.html" width="100%" height="100%" ref="iframeDom">iframe>
div>
template>
<script>
export default {
name: 'FAQ',
data() {
return {
data_: '哈哈哈,我----过去啦'
}
},
methods: {
// vue向iframe传递信息
vueSendMsg() {
//这里的ifranmeDom 对应 iframe标签中的ref属性的值 (ref="iframeDom")
const iframeWindow = this.$refs.iframeDom.contentWindow;
iframeWindow.postMessage({
cmd: 'myVue',
params: {
info: this.data_, //需要传递的数据
}
}, '*')
},
}
}
script>
<style scoped>
.main {
display: block;
width: 100%;
height: 600px;
}
style>
iframe引入的html中的写法:
<html>
<head>
<title>pViz cuslivingstone display exampletitle>
<link rel="stylesheet" type="text/css" href="js_css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="js_css/pviz-core.css">
<script src="js_css/pviz-bundle.min.js">script>
<style type="text/css" media="screen" class="example">
style>
head>
<body class="container">
<div class="row">
<h2>pViz custom display with css exampleh2>
div>
<h3>iframe嵌入的页面h3>
<script class="example">
window.addEventListener("message", function (event) {
var data = event.data;
// 然后就可以获得vue传过来的数据
console.log("从vue中获得的数据", data);
}, '*')
script>
body>
html>
暂时没用到—后续更新