在项目中遇到要嵌入第三方网页的需求,因为没有同第三方页面交互的需求,只需展示即可,所以最终决定使用 iframe 将第三方的网页嵌入到系统中,并且做到自适应效果。考虑到以后可能会怎加嵌入页面的数量,故而封装为组件,供以后复用:
上图为系统整体结构图,需要在内容区内展示 iframe 的内容,并且做到自适应。整体代码如下:
<template> <div class="iframe-container"> <iframe id="iframeContainer" :src="iframeUrl" frameborder="0" /> </div> </template> <script> import { mapGetters } from 'vuex' export default { name: 'IframeContainer', props: { iframeUrl: { type: String, default: '' } }, data() { return {} }, computed: { ...mapGetters([ 'sidebar' ]) }, watch: { 'sidebar.opened': { handler: function() { this.initIframe() }, immediate: true } }, mounted() { this.initIframe() window.onresize = () => { this.initIframe() } }, methods: { initIframe() { const iframeContainer = document.getElementById('iframeContainer') const deviceWidth = document.body.clientWidth const deviceHeight = document.body.clientHeight iframeContainer.style.width = this.sidebar.opened ? (Number(deviceWidth) - 293) + 'px' : (Number(deviceWidth) - 71) + 'px' iframeContainer.style.height = (Number(deviceHeight) - 110) + 'px' } } } </script> <style lang="scss" scoped> .iframe-container { width: 100%; height: 100%; } </style>
要做到嵌入的页面做到自适应的效果,首页保证 iframe 是自适应的,此处关键代码:
动态计算 iframe 的宽度和高度,计算时需要减去侧边栏宽度、内容区 padding、顶部导航高度等。
监听窗口大小改变时的事件,触发 iframe 宽度高度计算方法,重新为 iframe 设置宽度和高度:
如果系统侧边栏或者顶部导航是可收缩的,还需监听收缩事件,改变 iframe 高度和宽度:
此处监听 sidebar 的展开状态,在此不做过多赘述。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了