VueJS:将div内容绑定到iframe src

9
我在Vue文件中嵌入了这个pdf,但我想从一个定义了HTML表格的div中获取内容:
<template>
  <div id="editor"> HTML TABLE HERE </div>
  <iframe :src="iframe.src" type="application/pdf" width="100%" 
    height="650" frameborder="0" style="position:relative;z 
    index:999" ref="frame" @load="load" v-show="iframe.loaded">
  </iframe>
</template>

<script>
  export default {
    data() {
      return {
        iframe: {
          src: '', //DIV HERE #EDITOR
          loaded: false
        }
      }
    },
    methods: {
      load: function(){
        this.iframe.loaded = true;
      }
    }
  }
</script>

这是可能的吗?
1个回答

14

没问题!iframe的src属性会接收一个URL地址并尝试加载整个页面。因此,不要试图传递任何对编辑器div的引用,而是通过window.location.href传递当前URL。

然后,在编辑器div上设置ref属性,您可以在mounted生命周期钩子中引用它并获取其位置和尺寸。一旦您拥有了它,就可以将iframe和包装器div样式设置为仅显示“editor”的内容。

下面是整个过程(以及codepen):

<template>
  <div id="app">
    <div id="editor" ref="editor">HTML TABLE HERE</div>
    <div 
      id="iframe-wrapper"
      :style="iframe.wrapperStyle" 
    >
      <iframe 
        v-if="loaded"
        :src="iframe.src"
        :style="iframe.style"
        :height="iframe.style.height"
        :width="iframe.style.width"
        type="application/pdf"
        frameborder="0"
      ></iframe>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loaded: false,
      iframe: {
        src: window.location.href,
        style: null,
        wrapperStyle: null,
      }
    }
  },
  mounted() {
    let editor = this.$refs.editor;
    this.iframe.style = {
      position: 'absolute',
      width: window.innerWidth,
      height: window.innerHeight,
      top: -editor.offsetTop + "px",
      left: -editor.offsetLeft + "px",
    }    
    this.iframe.wrapperStyle = {
      overflow: 'hidden',
      height: editor.clientHeight + "px",
      width: editor.clientWidth + "px",
    } 
    this.loaded = true;
  }
}
</script>

2
在Chrome Version 66.0.3359.139上测试Codepen时,出现了CORS错误,无法加载。https://static.codepen.io/assets/telefon/bold/af889c53-1ee3-4868-8fdc-2b310d587b50-3-b7a87e0fbd213943fae0c0ef5985635dd43fa9c24876b2725127a13ccaf4ab6a.woff'的字体访问被CORS策略阻止:请求的资源上没有'Access-Control-Allow-Origin'头。因此,源'https://codepen.io'不允许访问。 - joshfindit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接