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

Vue-Grid-Layout多布局组件隐藏及低分辨率响应式适配问题咨询

问题1:隐藏组件后grid-item仍占位的解决方法

把v-if判断从内部的<component>移动到<grid-item>标签上,同时通过计算属性过滤激活的部件,避免修改原始布局配置:

// 新增计算属性
computed: {
  // 过滤部件布局中激活的项
  filteredWidgetLayout() {
    return this.layout.filter(item => item.isActive)
  }
}

修改部件区域的grid-item遍历逻辑:

<grid-item 
  v-for="(item, index) in filteredWidgetLayout" :key="index"
  :x="item.x"
  :y="item.y"
  :w="item.w"
  :h="item.h"
  :i="item.i"
  drag-allow-from=".vue-draggable-handle"
  drag-ignore-from=".no-drag"
>
  <component :is="item.c"></component>
</grid-item>

因为你已经开启了vertical-compact属性,隐藏项不渲染后,剩余的部件会自动向上紧凑排列,不会留空白位置,原始布局参数仍保留在layout数组中,需要恢复显示时直接修改对应项的isActive属性即可。

问题2:小屏设备卡片自适应单列排布的解决方法

监听窗口宽度变化,动态调整卡片布局的宽度和位置,同时保留桌面端原始布局用于切换恢复:

第一步:新增存储变量

data() {
  return {
    // 原有其他配置不变
    // 存储桌面端原始卡片布局
    originCardsLayout: JSON.parse(JSON.stringify([
      {"x":0,"y":0,"w":3,"h":4,"i":"0", "c": 'ManagedDevices', isActive: true}, 
      {"x":3,"y":0,"w":3,"h":4,"i":"1", "c": 'ActiveEndpoints', isActive: true},
      {"x":6,"y":0,"w":3,"h":4,"i":"2", "c": 'RoutingTraffic', isActive: true},  
      {"x":9,"y":0,"w":3,"h":4,"i":"3", "c": 'BridgingTraffic', isActive: true}, 
    ])),
    screenWidth: window.innerWidth
  }
}

第二步:新增监听和布局调整逻辑

mounted() {
  // 加防抖避免resize频繁触发更新
  const resizeHandler = this.debounce(() => {
    this.screenWidth = window.innerWidth
    this.adjustCardsLayout()
  }, 300)
  window.addEventListener('resize', resizeHandler)
  // 初始化时执行一次布局调整
  this.adjustCardsLayout()
},
beforeDestroy() {
  window.removeEventListener('resize', this.resizeHandler)
},
methods: {
  debounce(func, delay) {
    let timer = null
    return function() {
      clearTimeout(timer)
      timer = setTimeout(() => func.apply(this, arguments), delay)
    }
  },
  adjustCardsLayout() {
    // 768px为移动端断点,可根据需求调整
    if (this.screenWidth < 768) {
      this.cardsLayout = this.cardsLayout.map((item, index) => {
        return {
          ...item,
          w: 12, // 占满全部12列
          x: 0,
          y: index // 按顺序纵向排列
        }
      })
    } else {
      // 大屏恢复原始布局,同步隐藏状态
      this.cardsLayout = this.originCardsLayout.map(originItem => {
        const currentItem = this.cardsLayout.find(i => i.i === originItem.i)
        return {
          ...originItem,
          isActive: currentItem ? currentItem.isActive : originItem.isActive
        }
      })
    }
  }
}

内容的提问来源于stack exchange,提问作者Yasin Demirkaya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 15:39:02