组件
<template>
<div
class="ScaleBox"
:style="{
width: width + 'px',
height: height + 'px',
}"
>
<slot></slot>
</div>
</template>
<script setup>
import {
defineProps,
onMounted,
onUnmounted,
reactive,
toRef,
watch,
} from "vue";
import { debounce } from "@/util/scale.ts";
const props = defineProps({
width: Number,
height: Number,
});
const width = toRef(props, "width");
const height = toRef(props, "height");
let scale = reactive({
w: 1,
h: 1,
});
let getScale = () => {
const w = window.innerWidth / width.value;
const h = window.innerHeight / height.value;
let scale = w < h ? w : h;
return [scale, scale];
};
let setScale = (e) => {
scale.h = getScale()[0];
scale.w = getScale()[1];
};
let reCalc = debounce(setScale);
watch(
() => width.value,
() => {
setScale();
}
);
onMounted(() => {
setScale();
window.addEventListener("resize", reCalc);
});
onUnmounted(() => {
window.removeEventListener("resize", reCalc);
});
</script>
<script>
export default {
name: "ScaleBox",
};
</script>
<style lang="scss" scoped>
.ScaleBox {
position: absolute;
transform: scale(v-bind("scale.w"), v-bind("scale.h")) translate(-50%, -50%);
display: flex;
flex-direction: column;
transform-origin: top left;
left: 50%;
top: 50%;
transition: 0.2s;
z-index: 999;
}
</style>
使用
<script setup lang="ts">
const otherConfig = ref({
pageWidth: 1920,
pageHight: 1080,
});
otherConfig.value.pageHight = window.screen.availHeight;
otherConfig.value.pageWidth = window.screen.availWidth;
</script>
<template>
<ScaleBox
:width="otherConfig.pageWidth"
:height="otherConfig.pageHight"
style="background: #eeeeee"
>
</ScaleBox>
</template>