![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/1ad2a310d191184ffb9548b4d8b7e0ee.png)
代码: Iframe.vue
<template>
<div class="iframe">
<iframe
v-if="isRequestHeader"
id="myIframe"
name="myIframe"
src=""
frameborder="0"
scrolling="no"
/>
<iframe
v-else
id="myIframe"
name="myIframe"
:src="`${apiUrl}${url}`"
frameborder="0"
scrolling="no"
/>
</div>
</template>
<script>
import util from '@/utils/util'
import { getToken } from '@/utils/token'
export default {
name: 'Iframe',
props: {
url: {
type: String,
default: '',
required: true
},
isRequestHeader: {
type: Boolean,
default: false,
required: false
}
},
data () {
return {
apiUrl: util.apiUrl
}
},
watch: {
url: {
handler: function (newVal, oldVal) {
if (newVal && newVal !== oldVal) {
this.$nextTick(() => {
this.adaptWidthAndHeight()
})
}
}
}
},
created () {
if (this.isRequestHeader) {
setTimeout(() => {
const myIframe = document.querySelector('#myIframe')
this.populateIframe(myIframe, [['token', getToken()]])
}, 0)
}
},
mounted () {
this.adaptWidthAndHeight()
},
methods: {
adaptWidthAndHeight () {
const myIframe = document.getElementById('myIframe')
const deviceWidth = document.documentElement.clientWidth
const deviceHeight = document.documentElement.clientHeight
myIframe.style.width = (Number(deviceWidth) - 40) + 'px'
myIframe.style.height = (Number(deviceHeight) - 164) + 'px'
},
populateIframe (iframe, headers) {
var xhr = new XMLHttpRequest()
xhr.open('GET', `${this.apiUrl}${this.url}`)
xhr.responseType = 'blob'
headers.forEach((header) => {
xhr.setRequestHeader(header[0], header[1])
})
xhr.onreadystatechange = () => {
if (xhr.readyState === xhr.DONE) {
console.log('xhr.response', xhr.response)
if (xhr.status === 200) {
iframe.src = URL.createObjectURL(xhr.response)
}
}
}
xhr.send()
}
}
}
</script>
<style lang="scss" scoped>
.iframe {
width: 100%;
height: 100%;
}
</style>