You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Element Plus布局网格中根据窗口宽度动态设置pageSize?

解决方案

思路说明

Element UI的栅格断点有固定宽度阈值,我们可以通过监听窗口尺寸变化,判断当前处于哪个断点区间,再匹配对应的pageSize值,同时做防抖处理避免频繁触发计算。

Element默认断点阈值:

  • xs:<768px
  • sm:≥768px
  • md:≥992px
  • lg:≥1200px
  • xl:≥1920px

具体实现代码

在你的Vue组件中添加以下逻辑:

<template>
  <!-- 原有代码保持不变 -->
  <el-col
    v-for="i in listVariables.list"
    :key="i.id"
    :xs="12"
    :sm="12"
    :md="8"
    :lg="8"
    :xl="6"
  >
    <ProjectListItem :project-info="i" @refresh-list="getListData" />
  </el-col>

  <el-pagination :page-sizes="pageSize" />
</template>

<script>
export default {
  data() {
    return {
      pageSize: 6, // 默认xs/sm的pageSize
      breakpointPageMap: {
        xs: 6,
        sm: 6,
        md: 9,
        lg: 9,
        xl: 12
      },
      resizeTimer: null // 防抖计时器
    }
  },
  mounted() {
    // 初始化时计算一次pageSize
    this.calculatePageSize()
    // 监听窗口 resize 事件
    window.addEventListener('resize', this.handleResize)
  },
  beforeUnmount() {
    // 组件销毁前移除监听,避免内存泄漏
    window.removeEventListener('resize', this.handleResize)
    if (this.resizeTimer) clearTimeout(this.resizeTimer)
  },
  methods: {
    handleResize() {
      // 防抖:300ms内只执行一次计算
      if (this.resizeTimer) clearTimeout(this.resizeTimer)
      this.resizeTimer = setTimeout(() => {
        this.calculatePageSize()
      }, 300)
    },
    calculatePageSize() {
      const windowWidth = window.innerWidth
      let currentBreakpoint = 'xs'
      
      if (windowWidth >= 1920) {
        currentBreakpoint = 'xl'
      } else if (windowWidth >= 1200) {
        currentBreakpoint = 'lg'
      } else if (windowWidth >= 992) {
        currentBreakpoint = 'md'
      } else if (windowWidth >= 768) {
        currentBreakpoint = 'sm'
      }
      
      this.pageSize = this.breakpointPageMap[currentBreakpoint]
    }
  }
}
</script>

补充说明

  • 防抖处理:设置300ms延迟是为了避免窗口拖动过程中频繁触发计算,提升性能。
  • 如果你的项目中Element配置了自定义断点阈值,直接修改calculatePageSize里的宽度数值即可。
  • 初始化时执行一次calculatePageSize,保证页面加载时就匹配正确的pageSize。

内容的提问来源于stack exchange,提问作者卢方舟

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 09:16:15