vue中父元素动态获取iframe高度

背景:在vue开发中(不论是vue2还是vue3),我在页面中打印都可以拿到document.getElementById('iframe')的DOM节点,但就是在页面中不显示,需要等待iframe挂载上去,再进行响应的DOM操作,因此使用了setTimeout

例如:

<template>
  <iframe id="iframe" src="xxx" frameborder="0" class="iframe"></iframe>
</template>
<script>
  methods: {
    // 这里的viewer是iframe中的子元素,实际开发中我这里引入了pdfjs用来进行pdf在线展示,所以需要获取viewer的高度
    setIframeHeight(iframe) {
      let iframeWin = iframe.contentWindow || iframe.contentDocument.parentWindow
      if (iframeWin.document.getElementById('viewer')) {
        iframe.height = iframeWin.document.getElementById('viewer').scrollHeight
      }
    }
  },
  mounted() {
    let ths = this
    // 需要在iframe加载完成后调用该方法,或者在$nextTick中进行方法调用,看实际情况
    setTimeout(function() {
      ths.setIframeHeight(document.getElementById('iframe'))
    }, 1000)
  }
</script>

posted on 2022-12-04 16:01  铃之森  阅读(1008)  评论(0编辑  收藏  举报

导航