todo: 写一个适配所有容器的 layout ,而不仅仅是 window

⭐️ 核心步骤

  1. 创建一个 layout 父容器,专门做适配,把内容以插槽的形式放入
  2. layout 接收两个参数,设计稿上的 widthheight
  3. mounted 中计算设计稿和屏幕比例
    1. const w = window.innerWidth / this.width
    2. const h = window.innerHeight / this.height
    3. return w > h ? h : w
    4. this.style.transform = 'translate(-50%, -50%) scale(getScale())'
  4. 初始化计算一次,后续监听窗口 onresize 设置
  5. 页面设置样式都用设计稿上 px 写
<template>
  <div class="shell" :style="style">
    <!-- 页面以插件形式导入 -->
    <slot />
  </div>
</template>

<script>
export default {
  name: 'shell',
  // 放入设计稿长宽
  props: {
    width: {
      type: String | Number,
      default: '1920',
    },
    height: {
      type: String | Number,
      default: '1080'
    }
  },
  data() {
    return {
      style: {
        width: this.width + 'px',
        height: this.height + 'px',
        // 利用 left、top 50% + translate(-50%, -50%) 居中显示
        // 利用计算 scale 比例放大缩小容器
        transform: 'translate(-50%, -50%) scale(1)'
      }
    }
  },
  mounted() {
    this.setScale();
    // 监听 窗口 resize ,设置 scale
    window.onresize = this.$utils.debounce(this.setScale, 500, true);
  },
  methods: {
    // 根据长度比和宽度比,找出min者设置scale,保证屏幕显示完全
    getScale() {
      const w = this.$utils.getViewportSize().width / this.width;
      const h = this.$utils.getViewportSize().height / this.height;
      return w < h ? w : h;
    },
    // 设置scale
    setScale() {
      this.style.transform = `translate(-50%, -50%) scale(${this.getScale()})`;
      console.log(this.style.transform);
    }
  }
}
</script>

<style scoped lang="scss">
.shell {
  // 设置变形原点为左上角
  // transform-origin: 0 0;
  position: absolute;
  left: 50%;
  top: 50%;
  background-color: rgba(0, 0, 0, 0.1);
}
</style>

使用方式:

<template>
<Shell :width="3840" :height="1080">
  <div class="home">
    <div class="nav">
      <div class="title">XX集团版图展示</div>
  </div>
    <div class="main">
      <div id="myChart"></div>
  </div>
  </div>
  </Shell>
</template>