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()
    })
}
相关推荐
水月wwww3 小时前
vue学习之组件与标签
前端·javascript·vue.js·学习·vue
星光一影4 小时前
基于SpringBoot智慧社区系统/乡村振兴系统/大数据与人工智能平台
大数据·spring boot·后端·mysql·elasticsearch·vue
IT教程资源C17 小时前
(N_151)基于微信小程序校园学生活动管理平台
mysql·vue·前后端分离·校园活动小程序·springboot校园活动
AI3D_WebEngineer2 天前
企业级业务平台项目设计、架构、业务全解之组件库篇
前端·javascript·vue
木子李BLOG2 天前
vue.js设计与实现(待续)
vue
悟能不能悟2 天前
reason: unable to verify the first certificate 如何处理
vue
!win !3 天前
通过重写组件轻松掌握用JSX写Vue项目
vue·jsx
zy happy4 天前
RuoyiApp 在vuex,state存储nickname vue2
前端·javascript·小程序·uni-app·vue·ruoyi
小阳生煎4 天前
Vue实现全局设置一个刷新按钮 只刷新当面路由页面 不跳转操作功能
vue.js·vue
Zzzzzxl_4 天前
互联网大厂前端面试实录:HTML5、ES6、Vue/React、工程化与性能优化全覆盖
性能优化·vue·es6·react·html5·前端面试·前端工程化