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

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

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

实现原理

只简略说一下原理。

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

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

html 复制代码
<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 进行绑定时,可以这样写,就会同时触发多个:

js 复制代码
window.addEventListener('resize', () => {
    this.width = this.widthInit
    this.height = this.heightInit
    this.$nextTick(()=>{
        this.resize()
    })
})

下面这样就只能触发一个

js 复制代码
window.onresize = () => {
    this.width = this.widthInit
    this.height = this.heightInit
    this.$nextTick(()=>{
        this.resize()
    })
}
相关推荐
计算机学长felix28 分钟前
基于Django的“酒店推荐系统”设计与开发(源码+数据库+文档+PPT)
数据库·python·mysql·django·vue
陶甜也2 小时前
threeJS 实现开花的效果
前端·vue·blender·threejs
叫我阿柒啊19 小时前
从Java全栈到前端框架:一次真实面试的深度复盘
java·spring boot·typescript·vue·database·testing·microservices
借你耳朵说爱你21 小时前
浅拷贝和深拷贝两种不同的对象复制
vue·web
F2E_Zhangmo1 天前
基于cornerstone3D的dicom影像浏览器 第四章 鼠标实现翻页、放大、移动、窗宽窗位调节
vue·cornerstone·cornerstone3d·cornerstonejs
最好结果2 天前
ruoyi系统-vue-elementui 表格单元格点击复制功能实现:实践与问题解决
vue
叫我阿柒啊3 天前
从Java全栈到前端框架:一次真实的面试对话与技术解析
java·javascript·typescript·vue·springboot·react·前端开发
工业互联网专业3 天前
基于Spark的新冠肺炎疫情实时监控系统_django+spider
python·spark·django·vue·毕业设计·源码·课程设计