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()
    })
}
相关推荐
百锦再7 小时前
重新学习Vue中的按键监听和鼠标监听
javascript·vue.js·vue·计算机外设·click·up·down
飞翔的佩奇9 小时前
Java项目:基于SSM框架实现的忘忧小区物业管理系统【ssm+B/S架构+源码+数据库+毕业论文+开题报告】
java·数据库·mysql·vue·毕业设计·ssm框架·小区物业管理系统
百锦再2 天前
Vue中对象赋值问题:对象引用被保留,仅部分属性被覆盖
前端·javascript·vue.js·vue·web·reactive·ref
一笑code2 天前
vue/微信小程序/h5 实现react的boundary
微信小程序·vue·react
eric*16882 天前
尚硅谷张天禹老师课程配套笔记
前端·vue.js·笔记·vue·尚硅谷·张天禹·尚硅谷张天禹
喜欢敲代码的程序员3 天前
SpringBoot+Mybatis+MySQL+Vue+ElementUI前后端分离版:项目搭建(一)
spring boot·mysql·elementui·vue·mybatis
海的诗篇_3 天前
前端开发面试题总结-原生小程序部分
前端·javascript·面试·小程序·vue·html
sunbyte3 天前
50天50个小项目 (Vue3 + Tailwindcss V4) ✨ | DragNDrop(拖拽占用组件)
前端·javascript·css·vue.js·vue
skyymrj13 天前
Vue3 + Tailwind CSS 后台管理系统教程
前端·css·vue
程序猿小D13 天前
[附源码+数据库+毕业论文]基于Spring+MyBatis+MySQL+Maven+Vue实现的校园二手交易平台管理系统,推荐!
java·数据库·mysql·spring·vue·毕业设计·校园二手交易平台