首先定义了一个名叫ScreenContainerOptions的组件,需要传的参数如下

export type ScreenContainerOptions = {width?: string | numberheight?: string | numberscreenFit?: boolean // 是否开启屏幕自适应,不然会按比例显示}

组件的主要代码如下

onMounted(async () => {await initSize()updateSize()updateScale()window.addEventListener('resize', onResize)isReady.value = true // 执行完上面的方法后再渲染slot插槽})// 初始化宽高const initSize = () => {return new Promise((resolve) => {nextTick(() => {dom = refName.valueparentDom = refNameParent.value// 获取大屏的真实尺寸(不传值就是dom元素的宽高)widthRef.value = props.options?.width || dom.clientWidthheightRef.value = props.options?.height || dom.clientHeight// 获取屏幕尺寸,避免重复计算if (!screenWidthRef.value || !screenHeightRef.value) {screenWidthRef.value = window.screen.widthscreenHeightRef.value = window.screen.height}resolve(true)})})}// 更新宽高const updateSize = () => {dom.style.width = `${widthRef.value || screenWidthRef.value}px`dom.style.height = `${heightRef.value || screenHeightRef.value}px`}// 更新缩放比例const updateScale = () => {// window.innerWidth 获取当前展示区域的宽度const currentWidth = window.innerWidth// 获取大屏最终真实的宽度const realWidth = widthRef.value || screenWidthRef.value// 是否开启屏幕适配,不会按照比例const { screenFit } = props.options// 如果不想屏幕留白,而是自适应宽高的话let heightScale = 1// window.innerWidth 获取当前展示区域的宽度const currentHeight = window.innerHeight// 获取大屏最终真实的宽度const realHeight = heightRef.value || heightRef.valueif (screenFit) {heightScale = currentHeight / realHeight// if (parentDom) {// parentDom.style.height = dom.style.height = `${window.innerHeight}px` // 父容器宽度设置为原屏幕的宽度// }}// 算出缩放比例并赋值// 只需要根据宽度计算即可const scale = currentWidth / realWidthdom && (dom.style.transform = `scale(${scale}, ${screenFit ? heightScale : 1})`) // 不开启screenFit的话高度不需要缩放if (parentDom) {parentDom.style.width = `${window.innerWidth}px` // 父容器宽度设置为原屏幕的宽度screenFit && (parentDom.style.height = `${window.innerHeight}px`) // 父容器宽度设置为原屏幕的宽度}}// 浏览器resize事件触发回调const onResize = async () => {await initSize()await nextTick()updateScale()}

组件完整代码地址

https://github.com/jimchou-h/vue-study/blob/dev/src/components/ScreenContainer.vue