在现代前端开发中,创建一个能够自适应不同屏幕尺寸的用户界面是非常重要的。本文将介绍如何使用 Vue 3 创建一个可以根据浏览器窗口大小进行缩放的 Dashboard 组件。
以下是利用js来实现该功能的代码
在模板部分,我们创建了一个包含 main 和 dashboard 的结构。screenRef 用于引用 dashboard 组件,以便在 JavaScript 中进行操作。
<template>
<div class="main">
<div class="dashboard" ref="screenRef">
<slot></slot>
</div>
</div>
</template>
脚本部分
<script setup>
import { onMounted, ref, onBeforeUnmount } from "vue";
const screenRef = ref(null);
onMounted(() => {
scale();
window.addEventListener("resize", scale);
});
onBeforeUnmount(() => {
window.removeEventListener("resize", scale);
});
// 封装缩放方法
function getScale(_w = 1920, _h = 1080) {
const ww = window.innerWidth / _w;
const wh = window.innerHeight / _h;
return Math.min(ww, wh);
}
function scale() {
const scaleValue = getScale();
const element = screenRef.value;
if (element) {
element.style.transform = `scale(${scaleValue}) translate(-50%, -50%)`;
element.style.transformOrigin = "top left";
}
}
</script>
<style lang="scss" scoped>
.main {
position: relative;
width: 100vw;
height: 100vh;
background: rgba(0, 0, 0, 1);
}
.dashboard {
position: fixed;
top: 50%;
left: 50%;
transform-origin: left top;
width: 1920px;
height: 1080px;
overflow: hidden;
}
</style>
以下是利用ts来实现该功能的代码
<script setup lang="ts">
import { onMounted, ref, onBeforeUnmount } from "vue";
const screenRef = ref<HTMLElement | null>(null);
onMounted(() => {
scale();
window.addEventListener("resize", scale);
});
onBeforeUnmount(() => {
window.removeEventListener("resize", scale);
});
// 封装缩放方法
function getScale(_w: number = 1920, _h: number = 1080): number {
const ww = window.innerWidth / _w;
const wh = window.innerHeight / _h;
return Math.min(ww, wh);
}
function scale(): void {
const scaleValue = getScale();
const element = screenRef.value;
if (element) {
element.style.transform = `scale(${scaleValue}) translate(-50%, -50%)`;
element.style.transformOrigin = "top left";
}
}
</script>
<style lang="scss" scoped>
.main {
position: relative;
width: 100vw;
height: 100vh;
}
.dashboard {
position: fixed;
top: 50%;
left: 50%;
transform-origin: left top;
width: 1920px;
height: 1080px;
overflow: hidden;
}
</style>
getScale 函数计算当前窗口与默认宽高(1920x1080)的比例,并返回最小值,以确保内容在不同设备上都能良好显示。
function getScale(_w = 1920, _h = 1080) { const ww = window.innerWidth / _w; const wh = window.innerHeight / _h; return Math.min(ww, wh); }