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()
    })
}
相关推荐
huangyiyi6666617 小时前
轮询那些事儿
javascript·前端框架·vue·js
七仔的博客18 小时前
博客的加载速度和大小的优化、优化再优化
vue·博客·优化·gzip·live2d
duandashuaige1 天前
解决用electron打包Vue工程(Vite)报错electron : Failed to load URL : xxx... with error : ERR _CONNECTION_REFUSED
javascript·typescript·electron·npm·vue·html
java水泥工2 天前
旅游管理系统|基于SpringBoot和Vue的旅游管理系统(源码+数据库+文档)
spring boot·vue·计算机毕业设计·java毕业设计·旅游管理系统
duansamve2 天前
Vue3与Vue2中使用对比
vue
Jeffrey__Lin4 天前
解决ElementPlus使用ElMessageBox.confirm,出现层级低于el-table的问题
前端·javascript·elementui·vue·elementplus
麦麦大数据4 天前
F024 RNN+Vue+Flask电影推荐可视化系统 python flask mysql 深度学习 echarts
python·rnn·深度学习·vue·echarts·电影推荐
HECHEN****5 天前
Composition API 与 React Hook 很像,区别是什么?
vue·面试题
知识分享小能手5 天前
微信小程序入门学习教程,从入门到精通,项目实战:美妆商城小程序 —— 知识点详解与案例代码 (18)
前端·学习·react.js·微信小程序·小程序·vue·前端技术
cgsthtm5 天前
RuoYi.Net后端返回雪花ID前端精度丢失问题
oracle·vue·精度丢失·雪花id·ruoyi.net