vue项目中向子级iframe页面传递信息来实现路由跳转和样式的改变和子级向父级传递页面高度信息(跨域情况下)

418 阅读1分钟

项目需求 页面中嵌入了iframe 需要改变子级页面的样式

父级页面发送数据的代码

// 写在你要触发的事件中
click () {
  const sendData = {};
  const index = this.$route.path;
  let type = null;
  switch (index) {
      case '/AA':
          type = '/a';
          break;
      case '/BB':
          type = '/b';
          break;
  }
  sendData.path = type;
  // webpack编辑的时候也会触发postMessage这个方法 所以需要约定下数据的格式
  sendData.ret = 0;
  const oIframe = document.getElementById('iframe');
  oIframe.contentWindow.postMessage(sendData, '*');
}

父级页面接受子级页面数据

mounted() {
    const _this = this;
    const oIframe = document.getElementById('iframe');
    oIframe.src = 'http://xx.xx.com/';
    oIframe.style.width = '100%';
    oIframe.style.height = 'auto';
    // 处理兼容行问题
    if (oIframe.attachEvent) {
        oIframe.attachEvent('onload', function () {
            // iframe加载完毕以后执行操作
            _this.click();
            window.addEventListener('message', function(e) {
                const data = e.data;
                if (data.ret === 0) {
                // 接受子级页面的高度 并改变iframe的高度 
                    oIframe.style.height = data.height + 'px';
                }
            });
        });
    } else {
        oIframe.onload = function () {
            // iframe加载完毕以后执行操作
            _this.click();
            window.addEventListener('message', function(e) {
                const data = e.data;
                if (data.ret === 0) {
                // 接受子级页面的高度 并改变iframe的高度 
                    oIframe.style.height = data.height + 'px';
                }
            });
        };
    }
},

子级页面的代码

// 接收父级页面传递来的信息
mounted() {
  window.addEventListener( "message", (e) => {
  // 格式约定后 webpack编辑的时候不会触发
      if(e.data.ret === 0) {
          this.$nextTick(() => {
              const header: any = document.getElementsByClassName("header")[0];
              header.style.display= 'none';
              // 向父级发送数据
              const data = {
                  height: document.getElementsByClassName("content")[0].scrollHeight,
                  ret: 0,
              };
              window.parent.postMessage(data,'*');
          });
          const path = e.data.path;
          if(this.$route.path === path) return;
          this.$router.push({ path });
      }
  });
}