vue 如何制作一个跟随窗口大小变化而变化的组件

vue 如何制作一个跟随窗口大小变化而变化的组件

像下图中展示的那些统计数件就是跟随窗口变化而变化的,而且是几乎等比缩放的。

在这里插入图片描述

实现原理

只简略说一下原理。

  1. pinia 中记录一个窗口变化的高度值
  2. 给要变化的组件添加一个高度值
  3. 组件内部所有关于长度距离的值都通过这个传递的值生成

比如下面这个例子中的所有长度值都通过传递的唯一长度值 props.height 来生成

<template>
    <div :class="['home-count-up', type, {'shadow': hasShadow}]" @click="routeToPath"
         :style="`
         width: ${props.height * 2.5}px;
         padding: ${props.height * 5/ 50}px ${props.height * 13/ 50}px;
         border-radius: ${props.height * 6 / 50}px
         `">
        <div class="icon">
            <el-icon :size="props.height * 4 / 10" fill="black">
                <component :is="icon"/>
            </el-icon>
        </div>
        <div class="content">
            <div class="label" :style="`font-size: ${props.height * 7 / 50}px`">{{label}}</div>
            <CountUp class="value" :font-size="props.height * 15 / 50" :endVal="value"/>
        </div>
    </div>
</template>

这里有一个技巧:

当多个组件都需要跟 window.onresize 进行绑定时,可以这样写,就会同时触发多个:

window.addEventListener('resize', () => {
    this.width = this.widthInit
    this.height = this.heightInit
    this.$nextTick(()=>{
        this.resize()
    })
})

下面这样就只能触发一个

window.onresize = () => {
    this.width = this.widthInit
    this.height = this.heightInit
    this.$nextTick(()=>{
        this.resize()
    })
}

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-07 14:36:07       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-07 14:36:07       106 阅读
  3. 在Django里面运行非项目文件

    2024-06-07 14:36:07       87 阅读
  4. Python语言-面向对象

    2024-06-07 14:36:07       96 阅读

热门阅读

  1. Kotlin getter 和 setter

    2024-06-07 14:36:07       30 阅读
  2. # ROS 获取激光雷达数据 (Python实现)

    2024-06-07 14:36:07       27 阅读
  3. vue2 集成element 步骤

    2024-06-07 14:36:07       21 阅读
  4. 基于Spring Security添加流控

    2024-06-07 14:36:07       36 阅读
  5. LeetCode //C - 168. Excel Sheet Column Title

    2024-06-07 14:36:07       33 阅读