前言
之前都是vue2,现在改了一下vue3,直接封装组件,用起来很方便。
vue3组件封装
<template>
<div class="containerBox" ref="ContainerBox">
<slot></slot>
</div>
</template>
<script setup lang="ts">
import { reactive, ref, toRefs, onMounted } from 'vue';
const ContainerBox = ref();
const state = reactive({
scale: 1,
width: 1920, //根据屏幕进行设置
height: 937, //根据屏幕进行设置
});
const { scale, width, height } = toRefs(state);
const getScale = () => {
// 固定好16:9的宽高比,计算出最合适的缩放比
const wh = window.innerHeight / height.value;
const ww = window.innerWidth / width.value;
scale.value = ww < wh ? ww : wh;
};
const debounce = (fn: Function, delay: number = 500) => {
const delays = delay || 500;
let timer: any;
return function () {
const args = arguments;
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function () {
timer = null;
// @ts-ignore
fn.apply(this, args);
}, delays);
};
};
onMounted(() => {
getScale();
window.addEventListener('resize', debounce(getScale));
});
</script>
<style scoped>
.containerBox {
width: v-bind(width + 'px');
height: v-bind(height + 'px');
position: absolute;
transform: scale(v-bind(scale)) translate(-50%, -50%);
display: flex;
flex-direction: column;
transform-origin: 0 0;
left: 50%;
top: 50%;
transition: 0.3s;
z-index: 999;
}
</style>
引用
<template>
<ContainerBox>
<div class="container"></div>
</ContainerBox>
</template>
<script lang="ts" setup>
import ContainerBox from './component/ContainerBox.vue';
</script>