vue 中引入iframe,动态设置其src,遇到的一些小问题总结

1.重置其样式,去掉外框以及滚动条等

<iframe
        id="myIframe"
        ref="iframe_a"
        :src="mySrc"
        width="100%"
        height="100%"
        frameborder="no"
        border="0"
        marginwidth="0"
        marginheight="0"
        scrolling="no"
        allowtransparency="yes"
      />

2.在mounted里也找不到iframe 的dom元素,于是用了很笨的办法去处理,希望路过的大佬可以指点一下,有好的办法教教我好吗??

export default {
  data() {
    return {
      mySrc: '',
      loading: true, // 如果正在加载,就会盖住展示内容
      timer: null, // 第1个定时器
      timer1: null // 第2个定时器
    }
  },
  mounted() {
    if (this.$refs && this.$refs['iframe_a']) {
      this.setLoading(this.$refs['iframe_a'])
    } else {
      // console.log('延时加载第一次')
      clearTimeout(this.timer1)
      this.timer1 = setTimeout(() => {
        this.setLoading(this.$refs['iframe_a'])
      }, 500)
    }
  },
  destroyed() {
    this.timer = null
    this.timer1 = null
  },
  methods: {
    // 补坑函数1
    setLoading(iframeDom) {
      if (iframeDom) {
        // console.log('找到元素了,执行iframeDom.onload')
        const iframeD = document.getElementById('myIframeWebgl')
        iframeD.onload = () => {
          // console.log('加载完了-----------')
          this.loading = false
        }
        iframeD.src = this.setRoute()
      } else {
        this.setTim()
      }
    },
    // 补坑函数2
    setTim() {
      const iframeD = document.getElementById('myIframe')
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        // console.log('延时加载第----次')
        this.setLoading(iframeD)
      }, 200);
    },
  }
}

3.在此之前,加载完成的onload事件有时候不会触发,点击页面有时候没有反应,地址改了但是页面没有变动,于是解决如下:

问题在于: iframe的绑定地址的代码一定要放在onload下面,要不然就完了
如果使用原生来写,大概这样子

let myIframeDiv= document.querySelector('#myIframeDiv')
let iframe = document.createElement('iframe')
iframe.onload = () => {
console.log('这样子就没问题了')
}
iframe.src = this.src // 就是这一行代码,一定要注意哦
myIframeDiv.appendChild(iframe)

posted @ 2021-01-06 00:18  糖~豆豆  阅读(6452)  评论(2编辑  收藏  举报
Live2D