1 <template> 2 <div class="iframe"> 3 <iframe 4 v-if="isRequestHeader" 5 id="myIframe" 6 name="myIframe" 7 src="" 8 frameborder="0" 9 scrolling="no" 10 /> 11 <iframe 12 v-else 13 id="myIframe" 14 name="myIframe" 15 :src="`${apiUrl}${url}`" 16 frameborder="0" 17 scrolling="no" 18 /> 19 </div> 20 </template> 21 <script> 22 import util from '@/utils/util' 23 import { getToken } from '@/utils/token' 24 export default { 25 name: 'Iframe', 26 props: { 27 // 请求的URL 28 url: { 29 type: String, 30 default: '', 31 required: true 32 }, 33 // 是否携带请求头(例如:token) 34 isRequestHeader: { 35 type: Boolean, 36 default: false, 37 required: false 38 } 39 }, 40 data () { 41 return { 42 apiUrl: util.apiUrl 43 } 44 }, 45 watch: { 46 url: { 47 handler: function (newVal, oldVal) { 48 if (newVal && newVal !== oldVal) { 49 this.$nextTick(() => { 50 this.adaptWidthAndHeight() 51 }) 52 } 53 } 54 } 55 }, 56 created () { 57 if (this.isRequestHeader) { 58 setTimeout(() => { 59 const myIframe = document.querySelector('#myIframe') 60 this.populateIframe(myIframe, [['token', getToken()]]) 61 }, 0) 62 } 63 }, 64 mounted () { 65 this.adaptWidthAndHeight() 66 }, 67 methods: { 68 /** 69 * iframe-宽高自适应显示 70 */ 71 adaptWidthAndHeight () { 72 const myIframe = document.getElementById('myIframe') 73 const deviceWidth = document.documentElement.clientWidth 74 const deviceHeight = document.documentElement.clientHeight 75 // 数字是页面布局宽度差值 76 myIframe.style.width = (Number(deviceWidth) - 40) + 'px' 77 // 数字是页面布局高度差 78 myIframe.style.height = (Number(deviceHeight) - 164) + 'px' 79 }, 80 /** 81 * iframe 添加请求头 82 */ 83 populateIframe (iframe, headers) { 84 var xhr = new XMLHttpRequest() 85 // `${this.apiUrl}${this.url}` 请求的URL 86 xhr.open('GET', `${this.apiUrl}${this.url}`) 87 xhr.responseType = 'blob' 88 headers.forEach((header) => { 89 xhr.setRequestHeader(header[0], header[1]) 90 }) 91 xhr.onreadystatechange = () => { 92 if (xhr.readyState === xhr.DONE) { 93 console.log('xhr.response', xhr.response) 94 if (xhr.status === 200) { 95 iframe.src = URL.createObjectURL(xhr.response) 96 } 97 } 98 } 99 xhr.send() 100 } 101 } 102 } 103 </script> 104 <style lang="scss" scoped> 105 .iframe { 106 width: 100%; 107 height: 100%; 108 } 109 </style>
参考链接 https://blog.csdn.net/yjl13598765406/article/details/130871566
标签:vue,iframe,请求,url,xhr,token,myIframe From: https://www.cnblogs.com/xiaoqilaile/p/17864005.html