Vue3 大屏适配组件(Scale / Rem 双方案一键切换)

发布时间:2026/7/22 5:28:27
Vue3 大屏适配组件(Scale / Rem 双方案一键切换) ‍ 写在开头点赞 收藏 学会一键切换「整体 Scale 缩放」「Rem 等分适配」窗口自动监听 resize适配设计稿 1920*1080Vue3 全局直接引入用一、新建组件 ScreenAdapter.vuetemplatedivclassscreen-adapter:class{ scale-mode: type scale }!-- 大屏所有内容插槽 --slot //div/templatescript setupimport{onMounted, onUnmounted}fromvue;const propsdefineProps({// 适配模式scale / rem type:{type: String, default:scale, // 默认用不变形的scale validator: val[scale,rem].includes(val)}, // 设计稿宽高 designWidth:{type: Number, default:1920}, designHeight:{type: Number, default:1080}});letresizeFnnull;//1. Scale 整体缩放适配functioninitScale(){const wrapdocument.querySelector(.screen-adapter);if(!wrap)return;const clientWdocument.documentElement.clientWidth;const clientHdocument.documentElement.clientHeight;const scaleWclientW / props.designWidth;const scaleHclientH / props.designHeight;const scaleMath.min(scaleW, scaleH);wrap.style.transformtranslate(-50%, -50%)scale(${scale});}//2. Rem 等分适配 设计稿px直接写remfunctioninitRem(){const clientWdocument.documentElement.clientWidth;// 把屏幕分成100份 1rem1%屏幕宽 document.documentElement.style.fontSizeclientW /100px;}// 初始化适配functionadapterInit(){if(props.typescale){initScale();}else{initRem();}}onMounted((){adapterInit();resizeFnadapterInit;window.addEventListener(resize, resizeFn);});onUnmounted((){window.removeEventListener(resize, resizeFn);});/scriptstyle scopedhtml, body{margin:0;height:100%;overflow: hidden;}.screen-adapter{position: fixed;left:50%;top:50%;transform-origin:00;}/* Scale模式固定画布大小 */ .scale-mode{width: 1920px;height: 1080px;}/style二、页面中使用1. 用 Scale 模式推荐交付、地图大屏、不变形template!-- 只用包一层内部全部按1920*1080写px即可 --ScreenAdaptertypescale!-- 你的大屏页面内容 --divclasstitle智慧公路大屏/div/ScreenAdapter/templatescript setupimportScreenAdapter from/components/ScreenAdapter.vue;/scriptstyle.title{/* 直接写px不用任何换算 */ font-size: 36px;width: 400px;height: 80px;line-height: 80px;text-align: center;}/style2. 切换 Rem 模式内部项目、铺满全屏ScreenAdaptertyperem内部大屏内容/ScreenAdapterRem 用法规则设计稿多少 px直接写多少 rem设计稿 200px → width: 200rem字体 28px → font-size: 28rem不用计算、不用除以任何数。三、两种模式使用场景记住type“scale”对外交付、政府大屏、Mapbox/L7/GIS 地图优点不变形、像素级还原、适配所有屏写法全部写 pxtype“rem”内部后台、运维大屏、工期紧优点全屏无留白、开发快写法设计稿 px 直接换成 rem四、关键注意点Scale 模式下所有弹窗、ECharts、地图都要包在插槽里面不要单独挂 body不需要再写任何额外适配 JS组件已经封装好监听 resize以后所有大屏页面直接套这个组件改个 type 就能切换适配方案如果对您有所帮助欢迎您点个关注我会定时更新技术文档大家一起讨论学习一起进步。