Vue3 Hooks 页面等比例缩小

399 阅读2分钟

记录一下

这是一个 Vue 3 组件及其相关的 TypeScript 文件,用于在页面加载时进行缩放处理,并在窗口尺寸改变时保持缩放比例。下面是对代码的详细解释:

代码功能概述

  1. 组件加载时调用:在 Vue 组件的 onMounted 钩子中调用 UserScalePage 函数,以便在页面加载时设置缩放。
  2. 缩放处理UserScalePage 函数根据设备的浏览器宽度和高度,计算合适的缩放比例,并应用到 body 元素上。
  3. 响应窗口变化:使用 throttle 函数优化窗口大小调整事件的处理,避免频繁调用缩放函数。

Vue 组件部分

通常放在app.vue 里面

<template>
  <!-- Vue 组件的模板部分(如果有的话) -->
</template>

<script setup lang="ts">
import { onMounted } from 'vue';
import UserScalePage from './Hooks/UserScalePage';

let options = {
  targetX: 1920,
  targetY: 1080,
  targetRatio: 16 / 8,
};

onMounted(() => {
  UserScalePage(options);
});
</script>
  • options:定义了缩放的目标尺寸和比例。
  • onMounted:在组件挂载后调用 UserScalePage 函数,将 options 传递给它。

UserScalePage.ts 文件

import { onMounted, onUnmounted } from 'vue';
import _ from 'lodash';

export default function UserScalePage(opstion: any) {
  const resizeFunc = _.throttle(function () {
    // 当窗口大小发生改变时,重新计算缩放
    triggerScale();
  }, 100);

  function triggerScale() {
    // 从传入的参数中获取目标尺寸和比例
    let targetX = opstion.targetX || 1920;
    let targetY = opstion.targetY || 1080;
    let targetRatio = opstion.targetRatio || 16 / 9;

    // 获取当前浏览器视口的宽度和高度
    let currentX = document.documentElement.clientWidth || document.body.clientWidth;
    let currentY = document.documentElement.clientHeight || document.body.clientHeight;

    // 计算缩放比例
    let scaleRatio = currentX / targetX;
    let currentRatio = currentX / targetY;

    // 根据比率决定如何缩放
    if (currentRatio > targetRatio) {
      scaleRatio = currentY / targetY;
      document.body.style.width = `${targetX}px`;
      document.body.style.height = `${targetY}px`;
      document.body.style.transform = `scale(${scaleRatio}) translateX(-50%)`;
      document.body.style.left = '50%'; // 调整 body 元素的定位
    } else {
      document.body.style.width = `${targetX}px`;
      document.body.style.height = `${targetY}px`;
      document.body.style.transform = `scale(${scaleRatio})`;
    }
  }

  onMounted(() => {
    triggerScale();
    window.addEventListener('resize', resizeFunc);
  });

  onUnmounted(() => {
    window.removeEventListener('resize', resizeFunc);
  });
}

主要功能解释

  1. resizeFunc:使用 lodash 的 throttle 函数创建一个节流的窗口大小调整事件处理函数。这样可以避免频繁调用 triggerScale,提高性能。

  2. triggerScale:计算并应用缩放。首先,获取当前窗口的宽度和高度。然后,计算缩放比例并根据当前的宽高比调整 body 元素的 style 属性以适应目标尺寸。

  3. onMounted:组件挂载时调用 triggerScale 函数并为窗口的 resize 事件添加监听器。

  4. onUnmounted:组件卸载时移除 resize 事件监听器,防止内存泄漏。

注意事项

  • translateX(-50%)left: 50%:在将 body 元素居中时,translateX(-50%)left: 50% 的组合可能不会达到预期效果,因为 body 通常不是定位元素。可能需要对内部容器进行样式调整以实现居中效果。

  • opstion 参数:可能有拼写错误,应该是 options,这会影响代码的可读性和维护性。

总体来看,这段代码用于在不同屏幕尺寸下进行页面缩放,保持设计稿的视觉效果一致。