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()
    })
}
相关推荐
IT教程资源19 小时前
N-159基于springboot,vue,AI协同过滤算法旅游推荐系统
mysql·vue·前后端分离·springboot旅游推荐·协同过滤算法旅游推荐·ai旅游推荐
wanzhong23332 天前
开发日记13-响应式变量
开发语言·前端·javascript·vue
wanzhong23332 天前
开发日记14-vite配置多环境
服务器·前端·vue
刘一说2 天前
Vue3 组合式 API(Composition API):逻辑复用的革命性实践
vue.js·vue
天天打码3 天前
Svelte-无虚拟DOM、极致性能的现代高性能Web开发框架!
前端·node.js·vue·svelte
LXMXHJ3 天前
项目之html+javaScript
java·vue
期货资管源码3 天前
智星期货资管子账户软件pc端开发技术栈的选择
c语言·数据结构·c++·vue
@二十六3 天前
表格行拖拽排序
vue·react·表格拖拽
jay神4 天前
基于Java的水果网上订购平台
java·mysql·vue·springboot·计算机毕业设计
午安~婉5 天前
整理知识点
前端·javascript·vue