当前位置: 首页 > news >正文

vue3 可视化大屏自适应屏幕组件

首先定义了一个名叫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

http://www.lryc.cn/news/299853.html

相关文章:

  • SpringCloud入门概述
  • 刷题计划_冲绿名
  • 【微信小程序开发】小程序版的防抖节流应该怎么写
  • 单片机学习笔记---蜂鸣器播放提示音音乐(天空之城)
  • 软件实例分享,茶楼收银软件管理系统,支持计时计费商品销售会员管理定时语音提醒功能
  • clang前端
  • ARM:AI 的翅膀,还能飞多久?
  • 【C语言】常见字符串函数的功能与模拟实现
  • pyGMT初步使用
  • 神经网络 | CNN 与 RNN——深度学习主力军
  • thinkphp6入门(20)-- 如何上传图片、文件
  • 【Linux技术宝典】深入理解Linux基本指令:命令行新手指南
  • C++:Level1阶段测试
  • autojs自动化刷视频脚本
  • 鲁南制药“健康幸福中国年”主题航班,开启探寻健康与幸福的旅程
  • CISA知识点
  • C语言求解猴子分桃子
  • 本地部署 Stable Cascade
  • LeetCode 二叉树/n叉树的解题思路
  • opencv mat用法赋值克隆的操作和一些基本属性
  • 【使用IDEA总结】01——新增作者信息、方法参数返回值
  • ElasticSearch分词器和相关性详解
  • DolphinScheduler安装与配置
  • Qt之条件变量QWaitCondition详解
  • 作为国产大模型之光的智谱AI,究竟推出了多少模型?一篇文章带你详细了解!
  • 学习转置矩阵
  • AJAX——常用请求方法
  • sqlserver2012 解决日志大的问题
  • Vue3快速上手(三)Composition组合式API及setup用法
  • 【C++】内存五大区详解