几行代码实现vue3数据大屏自适应~~

简介: 几行代码实现vue3数据大屏自适应~~

一:适用场景

最近在搭建vue3+ts+vite的一个后台模板,再做数据大屏的时候,放大或缩小浏览器会导致页面盒子无法铺满以及不能按照初始比例渲染;最后找到了以下这个方法可以很好地让大屏按照比例放大缩小,希望可以帮到大家。

二:先看效果

2023-04-16 (4).png

大屏自适应

三:代码实现

<script setup lang='ts'>
  import {onMounted, ref} from 'vue';
  import {useRouter} from "vue-router";
  import * as echarts from 'echarts';
  import {init, EChartsOption} from 'echarts';
  import mapJson from './modules/china.json'
  const loading = ref(true)
  // 获取自适应的盒子,也就是包裹echarts的最外层父级盒子
  const dataScreenRef = ref<HTMLElement | null>(null);
  onMounted(() => {
    // 重点一:
    // 初始化时为外层盒子加上缩放属性,防止刷新界面时就已经缩放
    if (dataScreenRef.value) {
      dataScreenRef.value.style.transform = `scale(${getScale()}) translate(-50%, -50%)`;
      dataScreenRef.value.style.width = `1920px`;
      dataScreenRef.value.style.height = `1080px`;
    }
    // 初始化echarts
    initChart();
    // 重点二:
    // 为浏览器绑定事件
    window.addEventListener("resize", resize);
  });
  // 重点三:
  // 根据浏览器大小推断缩放比例
  const getScale = (width = 1920, height = 1080) => {
    let ww = window.innerWidth / width;
    let wh = window.innerHeight / height;
    return ww < wh ? ww : wh;
  };
  // 重点四:
  // 监听浏览器 resize 事件
  const resize = () => {
    if (dataScreenRef.value) {
      dataScreenRef.value.style.transform = `scale(${getScale()}) translate(-50%, -50%)`;
    }
    // 使用了 scale 的echarts其实不需要需要重新计算缩放比例
    // Object.values(dataScreen).forEach(chart => {
    //   chart && chart.resize();
    // });
  };
  // 注册echarts
  function initChart() {
    const myChart = init(document.getElementById('map') as HTMLDivElement)
    const myChart2 = init(document.getElementById('map2') as HTMLDivElement)
    const myChart3 = init(document.getElementById('map3') as HTMLDivElement)
    const myChart4 = init(document.getElementById('map4') as HTMLDivElement)
    const myChart5 = init(document.getElementById('map5') as HTMLDivElement)
    const myChart6 = init(document.getElementById('map6') as HTMLDivElement)
    echarts.registerMap('china', mapJson)
    const option = <EChartsOption>{
      backgroundColor: "transparent",
      series: [
        {
          type: "map",
          roam: false,
          top: 100,
          label: {
            normal: {
              show: true,
              textStyle: {
                color: "#fff",
              },
            },
            emphasis: {
              textStyle: {
                color: "#fff",
              },
            },
          },
          itemStyle: {
            normal: {
              borderColor: "#2ab8ff",
              borderWidth: 1.5,
              areaColor: "#12235c",
            },
            emphasis: {
              areaColor: "#2AB8FF",
              borderWidth: 0,
              color: "green",
            },
          },
          zoom: 1.5,
          roam: true,
          map: "china", //使用
        },
      ],
    }
    myChart.setOption(option)
    myChart2.setOption(option)
    myChart3.setOption(option)
    myChart4.setOption(option)
    myChart5.setOption(option)
    myChart6.setOption(option)
    window.addEventListener("resize", function () {
      myChart.resize();
      myChart2.resize();
      myChart3.resize();
      myChart4.resize();
      myChart5.resize();
      myChart6.resize();
    });
    setTimeout(() => {
      loading.value = false
    }, 2000)
  }
  // 返回首页
  const router = useRouter();
  function backIndex() {
    // console.log('关闭');
    router.push('/')
  }
  // 获取当前时间
  const currentDate = ref('');
  const a = ["日", "一", "二", "三", "四", "五", "六"];
  const week = ref(null);
  const str = ref('');
  const timeInterval = setInterval(()=>{
    currentDate.value = new Date().toLocaleString()
    week.value = new Date().getDay();
    str.value = "今天是星期"+ a[week.value]
  },1000)
</script>
<template>
  <div class="screen-bg" v-loading="loading">
    <div class="container" ref="dataScreenRef">
      <div class="header">
        <div class="date">{{currentDate + '&nbsp; &nbsp; &nbsp; ' + str}}</div>
        <div class="title">国内贫富差距分布图</div>
            <div class="light" @click="backIndex">
              <div></div>
              <div></div>
              <div></div>
              <div></div>
              X
            </div>
      </div>
      <div class="body">
        <div class="map-box">
          <div id="map"></div>
        </div>
        <div class="right-data">
          <div class="item-box">
            <div id="map2"></div>
          </div>
          <div class="item-box">
            <div id="map3"></div>
          </div>
        </div>
      </div>
      <div class="footer">
        <div class="item-box">
          <div id="map4"></div>
        </div>
        <div class="item-box">
          <div id="map5"></div>
        </div>
        <div class="item-box">
          <div id="map6"></div>
        </div>
      </div>
    </div>
  </div>
</template>
<style scoped lang='scss'>
  // 背景
  .screen-bg {
    width: 100%;
    height: 100%;
    background: url('@/assets/dataScreen/background-6.png') no-repeat;
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-position: center;
    background-size: 100% 100%;
    background-size: cover;
    .light {
      width: 40px;
      height: 30px;
      position: absolute;
      top: 42px;
      right: 40px;
      z-index: 99999;
      transform: translate(-50%, -50%);
      /* width: fit-content; */
      text-align: center;
      line-height: 30px;
      color: #ffffff;
      font-size: 20px;
      text-transform: uppercase;
      transition: 0.5s;
      letter-spacing: 4px;
      cursor: pointer;
      overflow: hidden;
    }
    .light:hover {
      background-color: #ffffff;
      color: #050801;
      box-shadow: 0 0 5px #ffffff,
      0 0 25px #ffffff,
      0 0 50px #ffffff,
      0 0 200px #ffffff;
    }
    .light div {
      position: absolute;
    }
    .light div:nth-child(1) {
      width: 100%;
      height: 2px;
      top: 0;
      left: -100%;
      background: linear-gradient(to right, transparent, #ffffff);
      animation: animate1 1s linear infinite;
    }
    .light div:nth-child(2) {
      width: 2px;
      height: 100%;
      top: -100%;
      right: 0;
      background: linear-gradient(to bottom, transparent, #ffffff);
      animation: animate2 1s linear infinite;
      animation-delay: 0.25s;
    }
    .light div:nth-child(3) {
      width: 100%;
      height: 2px;
      bottom: 0;
      right: -100%;
      background: linear-gradient(to left, transparent, #ffffff);
      animation: animate3 1s linear infinite;
      animation-delay: 0.5s;
    }
    .light div:nth-child(4) {
      width: 2px;
      height: 100%;
      bottom: -100%;
      left: 0;
      background: linear-gradient(to top, transparent, #ffffff);
      animation: animate4 1s linear infinite;
      animation-delay: 0.75s;
    }
    @keyframes animate1 {
      0% {
        left: -100%;
      }
      50%,
      100% {
        left: 100%;
      }
    }
    @keyframes animate2 {
      0% {
        top: -100%;
      }
      50%,
      100% {
        top: 100%;
      }
    }
    @keyframes animate3 {
      0% {
        right: -100%;
      }
      50%,
      100% {
        right: 100%;
      }
    }
    @keyframes animate4 {
      0% {
        bottom: -100%;
      }
      50%,
      100% {
        bottom: 100%;
      }
    }
    // 中心容器
    .container {
      position: fixed;
      top: 50%;
      left: 50%;
      z-index: 999;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      transition: all 0.3s;
      transform-origin: left top;
      /*!* 设置一个最小的宽度 *!*/
      min-width: 1500px;
      /* 设置一个最大的宽度 */
      max-width: 1500px;
      margin: 0 auto;
      padding-top: 20px;
      .header {
        position: relative;
        height: 77px;
        margin-bottom: 20px;
        background-image: url('@/assets/dataScreen/pic-12.png');
        background-repeat: no-repeat;
        background-size: cover;
        .date {
          position: absolute;
          left: 100px;
          top: 55%;
          transform: translateY(-50%);
          font-family: FZHei-B01S, Arial, sans-serif;
          font-size: 20px;
          color: rgb(255, 255, 255);
          font-weight: normal;
          justify-content: center;
          text-align: center;
        }
        .title {
          position: absolute;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
          font-family: FZHei-B01S, Arial, sans-serif;
          font-size: 30px;
          color: rgb(255, 255, 255);
          font-weight: normal;
          justify-content: center;
          text-align: center;
        }
      }
      .body {
        display: flex;
        justify-content: space-between;
        .map-box {
          width: 700px;
          height: 430px;
          margin-right: 20px;
          border-width: 2px;
          border-color: rgb(14, 71, 143);
          border-style: solid;
          // background-color: rgba(14, 71, 143, 0.32);
          // background-clip: padding-box;
          background-image: url('@/assets/dataScreen/border-2.gif');
          background-size: 100% 100%;
          background-repeat: no-repeat;
          filter: blur(0px);
          #map {
            width: 100%;
            height: 100%;
          }
        }
        .right-data {
          flex: 1;
          display: flex;
          justify-content: space-between;
          background-color: transparent;
          .item-box {
            width: 350px;
            border-width: 2px;
            border-color: rgb(14, 71, 143);
            border-style: solid;
            background-image: url('@/assets/dataScreen/border-2.gif');
            background-size: 100% 100%;
            background-repeat: no-repeat;
            filter: blur(0px);
            &:last-child {
              margin-right: 0;
            }
            #map2,
            #map3 {
              width: 100%;
              height: 100%;
            }
          }
        }
      }
      .footer {
        margin-top: 20px;
        display: flex;
        justify-content: space-between;
        .item-box {
          width: 440px;
          height: 250px;
          border-width: 2px;
          border-color: rgb(14, 71, 143);
          border-style: solid;
          background-image: url('@/assets/dataScreen/border-2.gif');
          background-size: contain;
          background-repeat: no-repeat;
          filter: blur(0px);
          #map4,
          #map5,
          #map6 {
            width: 100%;
            height: 100%;
          }
        }
      }
    }
  }</style>


目录
相关文章
|
JavaScript 前端开发 安全
Vue 3
Vue 3以组合式API、Proxy响应式系统和全面TypeScript支持,重构前端开发范式。性能优化与生态协同并进,兼顾易用性与工程化,引领Web开发迈向高效、可维护的新纪元。(238字)
1572 139
|
缓存 JavaScript PHP
斩获开发者口碑!SnowAdmin:基于 Vue3 的高颜值后台管理系统,3 步极速上手!
SnowAdmin 是一款基于 Vue3/TypeScript/Arco Design 的开源后台管理框架,以“清新优雅、开箱即用”为核心设计理念。提供角色权限精细化管理、多主题与暗黑模式切换、动态路由与页面缓存等功能,支持代码规范自动化校验及丰富组件库。通过模块化设计与前沿技术栈(Vite5/Pinia),显著提升开发效率,适合团队协作与长期维护。项目地址:[GitHub](https://github.com/WANG-Fan0912/SnowAdmin)。
1670 5
|
缓存 JavaScript 算法
Vue 3性能优化
Vue 3 通过 Proxy 和编译优化提升性能,但仍需遵循最佳实践。合理使用 v-if、key、computed,避免深度监听,利用懒加载与虚拟列表,结合打包优化,方可充分发挥其性能优势。(239字)
826 1
|
开发工具 iOS开发 MacOS
基于Vite7.1+Vue3+Pinia3+ArcoDesign网页版webos后台模板
最新版研发vite7+vue3.5+pinia3+arco-design仿macos/windows风格网页版OS系统Vite-Vue3-WebOS。
1438 11
|
JavaScript 安全
vue3使用ts传参教程
Vue 3结合TypeScript实现组件传参,提升类型安全与开发效率。涵盖Props、Emits、v-model双向绑定及useAttrs透传属性,建议明确声明类型,保障代码质量。
906 0
|
缓存 前端开发 大数据
虚拟列表在Vue3中的具体应用场景有哪些?
虚拟列表在 Vue3 中通过仅渲染可视区域内容,显著提升大数据列表性能,适用于 ERP 表格、聊天界面、社交媒体、阅读器、日历及树形结构等场景,结合 `vue-virtual-scroller` 等工具可实现高效滚动与交互体验。
1413 1
|
JavaScript 前端开发 UED
Vue 表情包输入组件的实现代码:支持自定义表情库、快捷键发送和输入框联动的聊天表情解决方案
本文详细介绍了在 Vue 项目中实现一个功能完善、交互友好的表情包输入组件的方法,并提供了具体的应用实例。组件设计包含表情分类展示、响应式布局、与输入框的交互及样式定制等功能。通过核心技术实现,如将表情插入输入框光标位置和点击外部关闭选择器,确保用户体验流畅。同时探讨了性能优化策略,如懒加载和虚拟滚动,以及扩展性方案,如自定义主题和国际化支持。最终,展示了如何在聊天界面中集成该组件,为用户提供丰富的表情输入体验。
1120 8
|
JavaScript 前端开发 UED
Vue 表情包输入组件实现代码及详细开发流程解析
这是一篇关于 Vue 表情包输入组件的使用方法与封装指南的文章。通过安装依赖、全局注册和局部使用,可以快速集成表情包功能到 Vue 项目中。文章还详细介绍了组件的封装实现、高级配置(如自定义表情列表、主题定制、动画效果和懒加载)以及完整集成示例。开发者可根据需求扩展功能,例如 GIF 搜索或自定义表情上传,提升用户体验。资源链接提供进一步学习材料。
1091 1
|
缓存 JavaScript UED
除了循环引用,Vue3还有哪些常见的性能优化技巧?
除了循环引用,Vue3还有哪些常见的性能优化技巧?
776 0
|
JavaScript
vue3循环引用自已实现
当渲染大量数据列表时,使用虚拟列表只渲染可视区域的内容,显著减少 DOM 节点数量。
532 0