Alyssa Reyes
Alyssa Reyes

Reputation: 2439

VueJS: Bind div content to iframe src

I have this pdf embedded on my Vue file, but I want to get the content from a div where I define the html table:

<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>

Is this possible?

Upvotes: 9

Views: 62170

Answers (1)

thanksd
thanksd

Reputation: 55634

It is possible! The iframe's src attribute takes in a URL address and will try to load the whole page. So, instead of trying to pass it any kind of reference to the editor div, pass it the current URL via window.location.href.

Then, by setting a ref attribute on the editor div, you can reference it in your mounted lifecycle hook and get it's position and dimension. Once you have that, you can style the iframe and a wrapper div to only show contents of the `editor.

Here's the whole thing (and a 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>

Upvotes: 14

Related Questions