Vues数据大屏适配scale缩放方案

1.首先在utils文件夹下创建一个drawMixin.js文件

// 屏幕适配 mixin 函数
// * 默认缩放值
const scale = {
  width: '1',
  height: '1',
}
// * 设计稿尺寸(px)
const baseWidth = 1920
const baseHeight = 1080
// * 需保持的比例(默认1.77778)
const baseProportion = parseFloat((baseWidth / baseHeight).toFixed(5))
export default {
  data () {
    return {
      // * 定时函数
      drawTiming: null
    }
  },
  mounted () {
    this.calcRate()
    window.addEventListener('resize', this.resize)
  },
  beforeDestroy () {
    window.removeEventListener('resize', this.resize)
  },
  methods: {
    calcRate () {
      const appRef = this.$refs["appRef"]
      if (!appRef) return
      // 当前宽高比
      const currentRate = parseFloat((window.innerWidth / window.innerHeight).toFixed(5))
      if (appRef) {
        if (currentRate > baseProportion) {
          // 表示更宽
          scale.width = ((window.innerHeight * baseProportion) / baseWidth).toFixed(5)
          scale.height = (window.innerHeight / baseHeight).toFixed(5)
          appRef.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`
        } else {
          // 表示更高
          scale.height = ((window.innerWidth / baseProportion) / baseHeight).toFixed(5)
          scale.width = (window.innerWidth / baseWidth).toFixed(5)
          appRef.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`
        }
      }
    },
    resize () {
      clearTimeout(this.drawTiming)
      this.drawTiming = setTimeout(() => {
        this.calcRate()
      }, 200)
    }
  },
}
2.创建html结构

<template>
  <div id="index" ref="appRef">
    <dv-loading v-if="loading">Loading...</dv-loading>
    <div class="home">
      ...
    </div>
  </div>
</template>
3.css样式

#index {
  color: #d3d6dd;
  width: 1920px;
  height: 1080px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  transform-origin: left top;
  overflow: hidden;
  .home {
    background: url("./../assets/image/bannerBG.png") no-repeat center center;
    background-size: 100% 100%;
    padding: 16px 16px 0 16px;
    width: 100%;
    height: 100%;
  }
}
4.在HomeView.vue文件中引入并混入drawMixin.js对象
import drawMixin from "../utils/drawMixin";

export default {
  mixins: [drawMixin],
  data() {},
  ...
}
5.概念分享

mixins(混入),官方的描述是一种分发 Vue 组件中可复用功能的非常灵活的方式,mixins 是一个 js 对象,它可以包含我们组件中 script 项中的任意功能选项,如:data、components、methods、created、computed 等等。我们只要将公用的功能以对象的方式传入 mixins 选项中,当组件使用 mixins 对象时所有 mixins 对象的选项都将被混入该组件本身的选项中来,这样就可以提高代码的重用性,并易于后期的代码维护。

猜你喜欢

转载自blog.csdn.net/start1018/article/details/132359448