vue3+vite3大屏可视化适配解决方案 - scale

1,494 阅读1分钟

封装组件 ResizeContainer.vue

<template>
  <div class="screen-wrapper" ref="screenRef">
    <div class="screen" id="screen">
       <slot></slot>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
const screenRef = ref()
const props = defineProps({
  isFoolScreen: {
    type: Boolean,
    default: true
  }
})
onMounted(() => {
  // 初始化自适应-在刚显示的时候就开始适配一次
  handleScreenAuto() // 绑定自适应函数-防止浏览器栏变化后不再适配(这里可做节流优化)
  window.onresize = () => dbScreenAuto()
})

const handleScreenAuto = () => {
  const w = 1920 // 设计稿的宽度
  const h = 960 // 设计稿的高度
  const clientWidth = screenRef.value.clientWidth
  const clientHeight = screenRef.value.clientHeight // 计算宽高缩放比例
  const scaleW = clientWidth / w
  const scaleH = clientHeight / h

  let transformScale
  // 是否全屏显示
  if (props.isFoolScreen) {
    // 不考虑比例,直接拉伸 (全屏)
    transformScale = `scale(${scaleW}, ${scaleH}) translate(-50%)`
  } else {
  
    const scale = clientWidth / clientHeight < w / h ? clientWidth / w : clientHeight / h
    transformScale = `scale(${scale}) translate(-50%)`
  }
  document.getElementById('screen').style.transform = transformScale
}

// 防抖 避免调整窗口大小时多次执行
const debounce = (cb, delay = 100) => {
  let timer
  return () => {
    console.log(1)
    clearTimeout(timer)
    timer = setTimeout(() => {
      cb && cb()
    }, delay)
  }
}
const dbScreenAuto = debounce(handleScreenAuto)
</script>

<style lang="less" scoped>
.screen-wrapper {
  height: 100%;
  width: 100%;

  .screen {
    display: inline-block;
    width: 1920px;
    height: 960px;
    transform-origin: 0 0;
    position: absolute;
    left: 50%;
    transition: 0.28s;
  }
}
</style>


使用在App.vue中

<template>
  <ResizeContainer>
      <div class='container'><router-view></router-view></div>
  </ResizeContainer>
</template>
<script setup>
import ResizeContainer from '@/components/ResizeContainer.vue'
</script>
<style>
// 这个样式很重要 不然可能会出现溢出导致出现滚动条
.container{
  height: 100%;
  width: 100%;
}
</style>

注意点: 在入口文件index.html中 一定要加上这个

 <style>
      html,
      body,
      #app{
       overflow:hidden;
       height:100%;
       }
 </style>