vue+iframe 添加请求头,自适应宽度和高度

在这里插入图片描述

代码: 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
    url: {
      type: String,
      default: '',
      required: true
    },
    // 是否携带请求头(例如:token)
    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: {
    /**
     * iframe-宽高自适应显示
     */
    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'
    },
    /**
     * iframe 添加请求头
     */
    populateIframe (iframe, headers) {
      var xhr = new XMLHttpRequest()
      // `${this.apiUrl}${this.url}` 请求的URL
      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>

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值