博客
关于我
vue嵌套iframe问题
阅读量:620 次
发布时间:2019-03-12

本文共 1828 字,大约阅读时间需要 6 分钟。

在项目中引用另一个项目时,选择使用iframe是一种有效的解决方案。在实际操作中,可能会遇到一些挑战,需要仔细分析并采取相应的解决措施。以下是针对遇到的问题的详细分析和解决方法。

1. router.go()失效问题

当多次修改iframe的src属性后,调用router.go(-1)时,发现无法实现路由后退,而是将iframe当作一个独立的窗口文档,未能正确更改父级项目的路由功能。这是因为改变src属性会导致路由状态混乱。

解决方法:

不通过改变iframe的src属性值来访问具体内容,而是使用window.location.replace(url)来替换iframe的内容。通过Vue项目的ref引用iframe,并在mounted生命周期钩子中添加load事件监听器:

this.$refs.iframe.contentWindow.location.replace(val);

这样可以确保路由的正常操作,不会干扰父级项目的路由状态。

2. 在iframe内的图片设置宽高问题

为了在iframe内的图片中设置宽度和高度,需要访问iframe的内容窗口并对img标签进行操作。

步骤:

  • 通过document.getElementById找到指定的iframe元素。
  • 获取iframe的contentWindow对象。
  • iframe加载完成后,访问contentWindow.document
  • 使用getElementsByTagName('img')找到第一个img元素。
  • 根据iframe的宽度和高度调整img的尺寸:
  • let iframe = document.getElementById("preview");let iwindow = iframe.contentWindow;iframe.addEventListener('load', function () {    let idoc = iwindow.document;    let img = idoc.getElementsByTagName('img')[0];    if (img) {        if (img.width >= img.height) {            img.width = iframe.clientWidth;            let top = (iframe.clientHeight - img.height) / 2;            img.style.marginTop = top + "px";        } else {            img.height = iframe.clientHeight;            let left = (iframe.clientWidth - img.width) / 2;            img.style.marginLeft = left + "px";        }    }});

    注意事项:

    • clientWidthclientHeight包括了border的宽度,需谨慎使用。
    • marginTopmarginLeft用于设置布局,确保图片居中显示。

    3. 控制台调试建议

    为了验证代码的正确性,可以在控制台中输出相关信息:

    // console.log("window", iwindow);// console.log("document", idoc);// console.log("html", idoc.documentElement);// console.log("head", idoc.head);// console.log("body", idoc.body);// console.log("img", idoc.getElementsByTagName('img')[0]);// console.log("iframeWidth", iframe.clientWidth);// console.log("imgWidth", idoc.body.getElementsByTagName('img')[0]);

    通过以上方法,可以确保iframe内的图片正确显示,并且不会干扰父级项目的路由功能。

    在实际应用中,根据具体项目需求调整代码,确保各项布局和功能的正常运行。

    转载地址:http://flrxz.baihongyu.com/

    你可能感兴趣的文章
    Postgresql CopyManager 流式批量数据入库
    查看>>
    PostgreSQL cube 插件 - 多维空间对象
    查看>>
    PostgreSQL Daily Maintenance - cluster table
    查看>>
    PostgreSQL on Linux 最佳部署手册
    查看>>
    PostgreSQL Oracle 兼容性之 - pipelined
    查看>>
    PostgreSQL Point-In-Time Recovery (Incremental Backup)
    查看>>
    postgresql Streaming Replication监控与注意事项
    查看>>
    postgresql 不需要付费_使用数据传输在PostgreSQL执行 外部连接运算符
    查看>>
    postgresql 主从配置_生产环境postgresql主从环境配置
    查看>>
    postgresql 函数&存储过程 ; 递归查询
    查看>>
    PostgreSQL 分组聚合查询中 filter 子句替换 case when
    查看>>
    PostgreSQL 同步流复制锁瓶颈分析
    查看>>
    PostgreSQL 备份与还原命令 pg_dump
    查看>>
    Postgresql 外部表插件postgres_fdw的安装和使用
    查看>>
    PostgreSQL 如何从崩溃状态恢复(上)
    查看>>
    PostgreSQL 存储过程基本语法
    查看>>
    PostgreSQL 实现批量更新、删除、插入
    查看>>
    PostgreSQL 导入 .gz 备份文件
    查看>>
    PostgreSQL 批量插入&更新数据时报错(ERROR: ON CONFLICT DO UPDATE command cannot affect row a second time)
    查看>>
    PostgreSQL 新增数据返回自增ID
    查看>>