当前位置: 移动技术网 > IT编程>脚本编程>vue.js > VUE页面中加载外部HTML的示例代码

VUE页面中加载外部HTML的示例代码

2017年12月12日  | 移动技术网IT编程  | 我要评论

哈乐士,7tv.cc,vjia优惠券

前后端分离,后端提供了接口。但有一部分数据,比较产品说明文件,是存在其他的服务器上的。

所以,在页面显示的时候,如果以页面内嵌的形式显示这个说明文件。需要搞点事情以达到想要的效果。

不同以往的iframe标签,那种方式比较low,另外有其他的一些bug。

本文思路是把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;

  ...
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网