本文主要介绍如何使用Vue框架实现页面的自动缩放
环境依赖:
Vue3
lodash.debounce
<template>
<div :style="styleObject" class="scale-box">
<slot></slot>
</div>
</template>
<script>
import debounce from 'lodash.debounce'
export default {
name: 'VisualView',
props: {
width: {
type: Number,
default: 1920,
},
height: {
type: Number,
default: 1080,
}
},
data() {
return {
scale: this.getScale(),
}
},
mounted() {
// 获取窗体初始大小
// this.width = window.innerHeight;
// this.height = window.innerHeight;
this.getScale();
window.addEventListener("resize", this.setScale);
},
computed: {
styleObject() {
return {
transform: `scale(${this.scale}) translate(-50%, -50%)`,
WebkitTransform: `scale(${this.scale}) translate(-50%, -50%)`,
width: this.width + "px",
height: this.height + "px",
}
}
},
methods: {
getScale() {
let ww = window.innerWidth / this.width;
let wh = window.innerHeight / this.height;
return ww < wh ? ww : wh;
},
// 设置防抖
setScale: debounce(function () {
this.scale = this.getScale();
}, 500),
},
beforeUnmount() {
window.removeEventListener("resize", this.setScale);
},
}
</script>
<style scoped>
.scale-box {
transform-origin: 0 0;
position: absolute;
transition: 0.3s;
left: 50%;
top: 50%;
}
</style>
在App.vue
使用
<template>
<VisualView>
<IndexView />
</VisualView>
</template>
<script>
import IndexView from './components/IndexView.vue'
import VisualView from './components/VisualView.vue'
export default {
name: 'App',
components: {
IndexView,
VisualView
}
}
</script>
<style>
#app {
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
html,
body,
#app,
.index {
height: 100%;
}
.mt10 {
margin-top: 10px;
}
.header {
font-size: 25px !important;
height: 40px;
}
.font-style {
color: #62C4C9 !important;
font-weight: bold !important;
}
.frosted-glass {
background-color: rgba(20, 36, 49);
border-radius: 8px;
padding: 10px;
}
body {
background-color: #0C111A;
overflow: hidden;
}
</style>