VUE页面实现加载外部HTML方法

前后端分离,后端提供了接口。但有一部分数据,比较产品说明文件,是存在其他的服务器上的。所以,在页面显示的时候,如果以页面内嵌的形式显示这个说明文件。需要搞点事情以达到想要的效果。本文主要和大家介绍VUE页面中加载外部HTML的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧,希望能帮助到大家。

不同以往的IFRAME标签,那种方式比较Low,另外有其他的一些BUG。

本文思路是把HTML请求以来,以v-html的形式加载到页面内部。注册全局组件【v-html-panel】

1.HtmlPanel.vue文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<template>
  <p>
   <mu-circular-progress :size= "40"  v- if = "loading" />
   <p v-html= "html" ></p>
  </p>
</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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<template>
  <p>
   <v-html-panel :url.asyc= "url1" ></v-html-panel>
   <v-html-panel :url.asyc= "url2" ></v-html-panel>
  </p>
</template>
<style scoped>
  p{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+正则条件判断下)

1
2
3
4
5
6
7
8
9
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;
 
  ...
}
转载地址: http://www.php.cn/js-tutorial-386304.html




猜你喜欢

转载自blog.csdn.net/wojiaomaxiaoqi/article/details/79416039