PC大屏适配方案

移动端常用的屏幕适配方案是rem+flex布局+vh/vw,今天主要记录vue2项目中PC端的大屏适配。网上也有较多的插件可用,比如amfe-flexible,postcss-pxtorem等等。由于我现在做的这个项目中大屏页面其实并不多,就三四个的样子,为了简单点就自己通过组件的方式实现的。 先说一下具体思路,定义一个公共组件,在组件里实现大屏适配逻辑,同时也可以加入一些其他的公共逻辑(比如定时刷新,全屏展示等等,根据具体的项目要求来),在组件中通过slot插槽的形式去容纳大屏的具体内容。代码如下:

<template>
  <div>
    <slot></slot>
  </div>
</template>
<script>
export default {
  name: 'ResizeWrap',
  data(){
    return {
      lastTime: 0,
      lazyFun: null,
    }
  },
  mounted() {
    this.resetTime();
    this.resetScreenSize()
  },
  beforeDestroy() {
    if (this.lazyFun) {
      clearTimeout(this.lazyFun)
    }
    window.removeEventListener('resize', this.throttle)
  },
  methods: {
    resetScreenSize () {
      this.lastTime = new Date()
      //窗口大小发送改变时自动调整
      window.addEventListener('resize', this.throttle)
      this.initSize()
    },
    throttle() {
      let startTime = new Date()
      let remain =  600 - (startTime - this.lastTime)
      clearTimeout(this.lazyFun)
      if (remain < 0) {
        this.lastTime = startTime
        this.initSize.call(this)
      } else {
        this.lazyFun = setTimeout(() => {
          this.initSize.call(this)
        }, remain)
      }
    },
    initSize() {
      // PC端 基准大小
      let baseSize = 100;
      let basePc = baseSize / 1920; // 表示1920 * 1080的设计图,使用100PX的默认值
      let vW = window.innerWidth; // 当前窗口的宽度
      let vH = window.innerHeight; // 当前窗口的高度

      // 非正常屏幕下的尺寸换算
      let dueH = vW * 1080 / 1920
      if (vH < dueH) {
        vW = vH * 1920 / 1080
      }
      let rem = vW * basePc; 
      // document.documentElement.style.fontSize = (rem/1.72<40?45:rem/1.72) + "px";
      document.documentElement.style.fontSize = rem + "px";
    }
  }
}
</script>

在main.js中注册组件:

// 大屏适配
import Resize from '@/components/Resize'
Vue.component('Resize', Resize)

在页面中使用:

<template>
  <Resize>
    <!-- 大屏内容(模板仅供参考) -->
    <div class="main">

       <!-- 头部标题部分 -->
      <div class="header"> </div>

      <!-- 内容部分 -->
      <div class="content"> 

        <!-- 左边 -->
        <div class="left"> 
          <!-- 模块1 -->
          <div class="module1"> </div>
          <!-- 模块2 -->
          <div class="module2"> </div>
        </div>

        <!-- 中间-->
        <div class="center"> 
           <!-- 模块1 -->
          <div class="module1"> </div>
          <!-- 模块2 -->
          <div class="module2"> </div>
        </div>

        <!-- 右边-->
        <div class="right"> 
          <!-- 模块1 -->
          <div class="module1"> </div>
          <!-- 模块2 -->
          <div class="module2"> </div>
        </div>
      </div>
    </div>
  </Resize>
</template>

css里高度和字体用rem作为单位。

更新于: 2024年11月19日