VueJS:将 div 内容绑定到 iframe src

Aly*_*yes 8 javascript iframe vue.js

我在我的 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>
Run Code Online (Sandbox Code Playgroud)

这可能吗?

tha*_*ksd 13

有可能的!iframe 的src属性接受一个 URL 地址并尝试加载整个页面。因此,与其尝试将任何类型的引用传递给编辑器 div,不如通过window.location.href.

然后,通过ref在编辑器 div 上设置一个属性,您可以在mounted生命周期挂钩中引用它并获取它的位置和尺寸。一旦你有了它,你就可以设置 iframe 和包装器 div 的样式,以仅显示`编辑器的内容。

这是整个事情(和一个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>
Run Code Online (Sandbox Code Playgroud)

  • 在 Chrome `Version 66.0.3359.139` 上测试 codepen 时,出现 CORS 错误并且无法加载。从产地`访问字体在'https://static.codepen.io/assets/telefon/bold/af889c53-1ee3-4868-8fdc-2b310d587b50-3-b7a87e0fbd213943fae0c0ef5985635dd43fa9c24876b2725127a13ccaf4ab6a.woff“https://codepen.io”有已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问源“https://codepen.io”。` (2认同)