VUE頁面實現加載外部HTML方法


前后端分離,后端提供了接口。但有一部分數據,比較產品說明文件,是存在其他的服務器上的。所以,在頁面顯示的時候,如果以頁面內嵌的形式顯示這個說明文件。需要搞點事情以達到想要的效果。本文主要和大家介紹VUE頁面中加載外部HTML的示例代碼,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧,希望能幫助到大家。
不同以往的IFRAME標簽,那種方式比較Low,另外有其他的一些BUG。

本文思路是把HTML請求以來,以v-html的形式加載到頁面內部。注冊全局組件【v-html-panel】

1.HtmlPanel.vue文件

<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>

2.htmlViewSample.vue

<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>

注意事項:

  1. 直接使用axios處理的GET請求,需要處理跨域
  2. 外部的css樣式會作用到顯示的html
  3. 同時加載的外部html里的script也可能會執行,需要按需處理下
  4. 外部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;
  ...
}

原文:https://www.php.cn/js-tutorial-386304.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM