VUE页面中加载外部HTML
方法1,用iframevue页面<template><button @click="invokeHtmlMethod">调用html种方法</button><div class="iframestyleset"><iframename = "iframeMap" id="iframeMapViewComponent"v-bind:src="ge
·
方法1,用iframe
vue页面
<template>
<button @click="invokeHtmlMethod">调用html种方法</button>
<div class="iframestyleset">
<iframe name = "iframeMap" id="iframeMapViewComponent" v-bind:src="getPageUrl"
width="100%" height="100%"
frameborder="0" scrolling="no" ref="iframeDom"
></iframe>
</div>
</template>
export default {
data() {
return {
getPageUrl: 'static/testMsgWithIframe.html'
}
},
created() {
// 初始化时为window绑定一个方法
window['vueDefinedMyProp'] = (receiveParams) => {
this.receiveParamsFromHtml(receiveParams)
}
},
methods: {
receiveParamsFromHtml(res) {
console.log(res)
},
invokeHtmlMethod() {
window.frames['iframeMap'].lodaTable()
},
}
html页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button onclick="invockIframeMethod()">点击调用iframe</button>
<script>
function invockIframeMethod() {
// 是用widow调用vue绑定的vueDefinedMyProp方法
window.parent['vueDefinedMyProp']('you are Superman!');
}
function lodaTable() {
let num = 10;
while (num>0){
console.log(`number : ${num}`);
num--;
}
}
</script>
</body>
</html>
结果:
方法2
把HTML请求以来,以v-html的形式加载到页面内部。注册全局组件【v-html-panel】
1.HtmlPanel.vue文件
<template>
<div>
<mu-circular-progress :size="40" v-if="loading"/>
<div v-html="html"></div>
</div>
</template>
<style>
</style>
<script>
export default{
// 使用时请使用 :url.sync=""传值
props: {
url: {
required: true
}
},
data () {
return {
loading: false,
html: ''
}
},
watch: {
url (value) {
this.load(value)
}
},
mounted () {
this.load(this.url)
},
methods: {
load (url) {
if (url && url.length > 0) {
// 加载中
this.loading = true
let param = {
accept: 'text/html, text/plain'
}
this.$http.get(url, param).then((response) => {
this.loading = false
// 处理HTML显示
this.html = response.data
}).catch(() => {
this.loading = false
this.html = '加载失败'
})
}
}
}
}
</script>
htmlViewSample.vue
<template>
<div>
<v-html-panel :url.asyc="url1"></v-html-panel>
<v-html-panel :url.asyc="url2"></v-html-panel>
</div>
</template>
<style scoped>
div{color:red}
</style>
<script>
export default{
data () {
return {
url1: '',
url2: ''
}
},
mounted () {
this.url1 = 'http://file.xxx.com/group1/M00/0C/F5/xxxxxxxx.html'
this.url2 = 'http://file.xxx.com/group1/M00/0D/3B/yyyyyyy.html'
},
methods: {
}
}
</script>
注意事项:
- 直接使用axios处理的GET请求,需要处理跨域
- 外部的css样式会作用到显示的html
- 同时加载的外部html里的script也可能会执行,需要按需处理下
- 外部HTML文件内部的相对路径将不会被自动识别,绝对路径可以
NGINX跨域配置:
(Origin如果使用*的话,好像会出错,这里直接使用请求源的地址,如果担心安全性的话,可以用if+正则条件判断下)
location / {
add_header Access-Control-Allow-Origin $http_origin;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Methods GET;
access_log /data/nginx/logs/fdfs_https.log main;
...
}
更多推荐
已为社区贡献8条内容
所有评论(0)