业务需求写了个iframe通用组件:
1.高度自适应(在onload事件里手动获取内容高度给到iframe)
2.在窗口resize的时候,高度随着iframe内部内容高度响应变化
<template>
<div class="iframe-block-wrap">
<iframe
v-if="iframeId && iframeData"
:id="iframeId"
:srcdoc="iframeData"
:frameborder="frameborder"
:scrolling="scrolling"
:width="width"
@load="onloadFn"
></iframe>
</div>
</template>
<script lang="ts">
export default {
name: 'IframeBlock',
props: {
data: {
default: ''
},
width: {
default: '100%'
},
frameborder: {
default: '0'
},
scrolling: {
default: 'no'
},
styleConfig: {
default: '<style> *{margin: 0; padding: 0}</style>'
}
},
components: {},
data() {
return {
iframeId: '',
iframeData: '',
timer: null
}
},
watch: {
data(data) {
this.iframeData = this.styleConfig + data
}
},
mounted() {
this.iframeId = 'iframe' + new Date().getTime()
window.addEventListener('resize', this.resizeFn)
},
destroyed() {
window.removeEventListener('resize', this.resizeFn)
},
methods: {
onloadFn() {
this.$nextTick(() => {
var ifm = document.getElementById(this.iframeId)
if (ifm) {
let bodyDom = ifm.contentDocument
if (!bodyDom) {
bodyDom =
document.frames && document.frames[this.iframeId]
? document.frames[this.iframeId].document
: null
}
if (bodyDom) {
ifm.style.height = 'auto' //关键这一句,先取消掉之前iframe设置的高度
ifm.style.height = bodyDom.body.scrollHeight + 'px'
}
}
})
},
resizeFn() {
if (!this.timer) {
this.timer = true
setTimeout(() => {
this.onloadFn()
this.timer = false
}, 500)
}
}
}
}
</script>
亲测可用