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

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值