JS 互相调用iframe页面中js方法、VUE里 iframe 互调方法

1,父 html 调用子 iframe 内方法: 

document.getElementById("iframe").contentWindow.func(data1,data2...);

2,子 Iframe 中 调用 父html中方法

parent.func(data1,data2...)

在VUE中:

// 父vue文件调用 iframe html文件中方法:
this
.$refs.iframe.contentWindow.func(data1,data2...);
// 在 iframe 的 html文件中,调父 vue 中方法: (这里有点麻烦,.html 非vue组件,得借用js的全局变量做桥梁来实现)
data(){
return: {
     randomObj: {
      edit: 'edit_' + new Date().getTime()   // 先定义随机ID
     }
    }
  },
 created() {
     let _this = this;
     //这里可放到全局,提供给子 iframe 调用
window[this.randomObj.edit] = (_this) => {
this.module_edit(_this) //VUE 中方法
}
  },
// iframe.html 调用 vue 中方法
  var fatherId = null
  把 randomObj 传过来,再使用即可
  window.parent[fatherId.edit](_this)
//如果简单粗暴点,直接load 最方便:
<iframe ref="iframe" src="/static/index.html" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" width="100%" height="100%" @load="vueFunc"></iframe>
...
methods:{
  vueFunc(){}
}

iframe 上自适应高


<iframe ref="iframe" src="/static/index.html" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" width="100%" height="100%" @load="vueFunc"></iframe> 
...
methods:{
    vueFunc() {
      try {
        setTimeout(function() {

          let autoHeight = _this.$refs.iframe.contentWindow.document.documentElement.scrollHeight;
          _this.$refs.iframe.style.height = autoHeight + "px";

        }, 20);
      } catch (err) {
          console.log("vueFunc ");
      }
    },
}

.

原文地址:https://www.cnblogs.com/xiangsj/p/5895917.html