Vue 页面自动缩放

本文主要介绍如何使用Vue框架实现页面的自动缩放
环境依赖:

  1. Vue3
  2. 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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值