TDesign Starter Vue2路由嵌入iFrame

在实际项目上,存在引入其他网页内容到项目中,例如

iframe.gif

实现原理:在切换路由的时候判断是否为外部,如果是外部就动态创建iframe,切换就是隐藏显示iframe,关闭就是删除元素


image.png

第一步:增加iframe路由,实现切换

image.png

第二步:增加一个与内容区域一致的元素

image.png

第三步:监听路由,打开(创建)frame和关闭frame

image.png
增加两个方法,
/**
     * 打开一个frame
     */
    openFrame(menu) {
      const parent = document.getElementById('iframe');
      const children = parent.childNodes;
      let newPage = true;
      // eslint-disable-next-line no-restricted-syntax
      for (const i in children) {
        if (children && children[i] && children[i].nodeName === 'IFRAME') {
          const childrenPage = children[i];
          if (childrenPage.id === `menu-${menu ? menu.menuCode : ''}`) {
            childrenPage.setAttribute('style', 'width:100%;height:calc(100vh - 234px);visibility:visible');
            newPage = false;
          } else {
            childrenPage.setAttribute('style', 'width:0;height:0;visibility:hidden');
          }
        }
      }
      if (menu && newPage) {
        this.$message.loading('正在加载...');
        const newIframe = document.createElement('iframe');
        newIframe.setAttribute('frameborder', '0');
        newIframe.setAttribute('style', 'width:100%;height:calc(100vh - 234px);');
        newIframe.id = `menu-${menu.menuCode}`;
        newIframe.src = menu.pageFile;
        parent.appendChild(newIframe);
        newIframe.onload = () => {
          newIframe.setAttribute('style', 'width:100%;height:calc(100vh - 234px);visibility:visible');
          this.$message.closeAll();
        };
      }
    },
    removeFrame(path) {
      const menu = this.menuPathMap[path];
      if (menu && menu.path.indexOf('/iframe') === 0) {
        const parent = document.getElementById('iframe');
        const children = parent.childNodes;
        // eslint-disable-next-line no-restricted-syntax
        for (const i in children) {
          if (children && children[i] && children[i].nodeName === 'IFRAME') {
            const childrenPage = children[i];
            if (childrenPage.id === `menu-${menu.menuCode}`) {
              childrenPage.remove();
            }
          }
        }
      }
    },

第四步:结合页签tab的关闭,同时关闭frame

你可能感兴趣的:(TDesign Starter Vue2路由嵌入iFrame)