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()
    })
}
相关推荐
狼性书生14 小时前
uniapp实现的简约美观的星级评分组件
前端·uni-app·vue·组件
宇宙的最后一粒尘埃1 天前
Typeerror: cannot read properties of undefined (reading ‘XXX‘)
vue
清幽竹客2 天前
vue-18(使用 Vuex 插件实现高级功能)
前端·vue.js·前端框架·vue
牧码岛2 天前
Web前端之隐藏元素方式的区别、Vue循环标签的时候在同一标签上隐藏元素的解决办法、hidden、display、visibility
前端·css·vue·html·web·web前端
MINO吖2 天前
基于 qiankun + vite + vue3 构建微前端应用实践
vue·vite·微前端·qiankun·single-spa
Luffe船长2 天前
elementUI点击浏览table所选行数据查看文档
javascript·elementui·vue
IT瘾君3 天前
JavaWeb:前端工程化-ElementPlus
前端·elementui·node.js·vue
sunbyte4 天前
50天50个小项目 (Vue3 + Tailwindcss V4) ✨ | Dad Jokes(冷笑话卡片)
前端·javascript·css·vue.js·vue
幽络源小助理4 天前
SpringBoot+Vue+微信小程序校园自助打印系统
java·spring boot·微信小程序·小程序·vue
霸王蟹6 天前
从前端工程化角度解析 Vite 打包策略:为何选择 Rollup 而非 esbuild。
前端·笔记·学习·react.js·vue·rollup·vite