使用不带src属性的vuejs在iframe中渲染Component

Vis*_*iya 5 html iframe vue.js

<iframe id="frame" width="100%" height="100%">

</ifrme>
Run Code Online (Sandbox Code Playgroud)

我想在这个iframe中渲染组件.有没有在iframe中创建html元素或渲染组件的选项?

new Vue({
   el:'#frame',
   store:store,
   router:router,
   render: component
})
Run Code Online (Sandbox Code Playgroud)

Bed*_*ang 10

对我来说最简单的方法是使用srcdoc属性。它加载覆盖 src 属性的原始 html。

<template>
    <iframe :srcdoc="html"></iframe>
</template>
Run Code Online (Sandbox Code Playgroud)


Vis*_*iya 7

你可以参考下面的链接,这对我帮助很大.这是链接和代码片段.

Vue.component('i-frame', {
 render(h) {
 return  h('iframe', {
 on: { load: this.renderChildren }
})
},
beforeUpdate() {
//freezing to prevent unnessessary Reactifiation of vNodes
this.iApp.children = Object.freeze(this.$slots.default)
},  
methods: {
renderChildren() {
  const children = this.$slots.default
  const body = this.$el.contentDocument.body      
  const el = document.createElement('DIV') // we will mount or nested app to this element
  body.appendChild(el)

  const iApp = new Vue({
    name: 'iApp',
    //freezing to prevent unnessessary Reactifiation of vNodes
    data: { children: Object.freeze(children) }, 
    render(h) {
      return h('div', this.children)
    },
  })

  iApp.$mount(el) // mount into iframe

  this.iApp = iApp // cache instance for later updates


   }
  }
  })

   Vue.component('test-child', {
    template: `<div>
    <h3>{{ title }}</h3>
     <p>
     <slot/>
     </p>
    </div>`,
    props: ['title'],
    methods: {
     log:  _.debounce(function() {
     console.log('resize!')
     }, 200)
     },
     mounted() {
      this.$nextTick(() => {
        const doc = this.$el.ownerDocument
       const win = doc.defaultView
       win.addEventListener('resize', this.log)
     })
     },
      beforeDestroy() {
     const doc = this.$el.ownerDocument
     const win = doc.defaultView
     win.removeEventListener('resize', this.log)
     }  
     })

     new Vue({
      el: '#app',
      data: {
       dynamicPart: 'InputContent',
       show: false,
       }
      })
Run Code Online (Sandbox Code Playgroud)

https://jsfiddle.net/Linusborg/ohznser9/

  • 起初我不太清楚的是 Linusborg 的链接示例在他的模板中没有使用真正的 &lt;iframe&gt;。他创建了一个名为“i-frame”的自定义组件,该组件在 iframe 中呈现自身。换句话说,它没有直接展示如何将内容绑定到 iframe。它创建了一个组件,其行为有望满足您的要求。 (2认同)