vue3使用scale属性来实现大屏自适应铺满整个屏幕

<template>
    <div v-bind:style="styleObject" class="scale-box">
        <slot></slot>
    </div>
</template>

<script setup>
import debounce from "lodash/debounce";
import { computed, reactive } from "vue";
let that = reactive({
    width: 1920,
    height: 1080,
    scaleX: null,
    scaleY: null,
});
let styleObject = computed(() => {
    let obj = {
        transform: `scale(${that.scaleX},${that.scaleY}) translate(-50%, -50%)`,
        WebkitTransform: `scale(${that.scaleX},${that.scaleY}) translate(-50%, -50%)`,
        width: that.width + "px",
        height: that.height + "px",
    };
    return obj;
});

const getScale = () => {
    // 分别计算X轴和Y轴的缩放比例
    that.scaleX = window.innerWidth / that.width;
    that.scaleY = window.innerHeight / that.height;
};

const setScale = debounce(() => {
    // 获取到缩放比,设置它
    getScale();
}, 500);

onMounted(() => {
    getScale();
    window.addEventListener("resize", setScale);
});

onUnmounted(() => {
    window.addEventListener("resize", setScale);
});
</script>

<style lang="scss" scoped>
.scale-box {
    transform-origin: 0 0;
    position: absolute;
    left: 50%;
    top: 50%;
    transition: 0.3s;
}
</style>

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
对于Vue 3和Vite的大屏自适应,你可以使用CSS的媒体查询和Vue的响应式特性来实现。 首先,为了让你的大屏页面能够自适应不同的屏幕尺寸,你可以使用CSS的媒体查询来设置不同的样式。在你的Vue组件中,通过在<style>标签内添加媒体查询,根据不同的屏幕尺寸应用不同的样式。例如: ```html <template> <div class="container"> <!-- 页面内容 --> </div> </template> <style> .container { /* 普通屏幕样式 */ } @media screen and (min-width: 1200px) { .container { /* 大屏幕样式 */ } } </style> ``` 在上述示例中,`.container` 类选择器设置了普通屏幕下的样式,而`@media` 媒体查询选择器用于设置大屏幕下的样式,当屏幕宽度大于等于1200px时生效。 此外,Vue 3还提供了响应式特性,你可以使用`ref`或`reactive`来定义响应式数据,并在模板中根据不同的屏幕尺寸动态渲染内容。例如: ```html <template> <div> <h1 v-if="isLargeScreen">大屏幕内容</h1> <h1 v-else>普通屏幕内容</h1> </div> </template> <script> import { ref, onMounted, onBeforeUnmount } from 'vue' export default { setup() { const isLargeScreen = ref(false) const handleResize = () => { isLargeScreen.value = window.innerWidth >= 1200 } onMounted(() => { window.addEventListener('resize', handleResize) handleResize() }) onBeforeUnmount(() => { window.removeEventListener('resize', handleResize) }) return { isLargeScreen } } } </script> ``` 上述示例中,我们使用`ref`定义了一个名为`isLargeScreen`的响应式变量,并通过`window`对象的`resize`事件来监听窗口大小变化。在模板中,根据`isLargeScreen`的值来动态渲染不同的内容。 希望以上信息能对你有所帮助!如有更多问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值