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

Vue中如何将表格单行布局改为双列网格布局?

实现Vue模板的两列布局(填充完第一列再填第二列)

嘿,你这个需求其实很常见,放弃<table>改用<div>布局完全是正确的思路,这里给你两种靠谱的实现方案,你可以根据自己的场景选择:

方案一:拆分数组手动分列(更灵活可控)

这种方法是把templates数组拆分成左右两个子数组,分别渲染到两列中,能精准控制每列的内容数量,还能给两列单独加样式。

步骤1:添加计算属性拆分数组

在你的Vue组件的computed里添加一个计算属性,把数组分成大致相等的两部分:

computed: {
  splitTemplates() {
    // 计算中间位置,向上取整保证第一列不会比第二列少
    const midpoint = Math.ceil(this.templates.length / 2);
    return {
      leftColumn: this.templates.slice(0, midpoint),
      rightColumn: this.templates.slice(midpoint)
    };
  }
}

步骤2:修改模板结构

把原来的表格结构替换成div容器,分别渲染左右两列的内容:

<div class="template-grid-container">
  <!-- 第一列 -->
  <div class="template-column">
    <div v-for="template in splitTemplates.leftColumn" :key="template.id" class="template-item">
      <a @click="create(template.id)" class="hand-hover">
        <i :class="`fa fa-${template.icon} fa-fw`"></i>
        <strong>{{ template.label }}</strong>
      </a>
    </div>
  </div>

  <!-- 第二列 -->
  <div class="template-column">
    <div v-for="template in splitTemplates.rightColumn" :key="template.id" class="template-item">
      <a @click="create(template.id)" class="hand-hover">
        <i :class="`fa fa-${template.icon} fa-fw`"></i>
        <strong>{{ template.label }}</strong>
      </a>
    </div>
  </div>
</div>

步骤3:添加CSS样式

给容器和列设置样式,实现两列等宽布局:

.template-grid-container {
  display: flex;
  gap: 20px; /* 两列之间的间距,可自定义 */
}

.template-column {
  flex: 1; /* 让两列宽度自动平分可用空间 */
}

.template-item {
  padding: 8px 0; /* 保持和原来表格行类似的上下间距 */
  width: 400px; /* 保留你原来设置的400px宽度,也可以去掉让它自适应 */
}

方案二:CSS多列布局(更简洁)

如果不需要精准控制每列的数量,用CSS的column-count属性可以快速实现自动分列,不用修改数组结构,代码更简洁。

修改模板结构

直接把每个模板项放到一个容器里:

<div class="template-columns-container">
  <div v-for="template in templates" :key="template.id" class="template-item">
    <a @click="create(template.id)" class="hand-hover">
      <i :class="`fa fa-${template.icon} fa-fw`"></i>
      <strong>{{ template.label }}</strong>
    </a>
  </div>
</div>

添加CSS样式

用CSS多列属性实现自动分列:

.template-columns-container {
  column-count: 2; /* 指定分成2列 */
  column-gap: 20px; /* 列间距 */
  width: 820px; /* 400px*2 + 20px间距,也可以设为100%自适应 */
}

.template-item {
  break-inside: avoid; /* 防止单个模板项被拆分到两列中 */
  padding: 8px 0;
  width: 400px;
}

两种方案对比

  • 方案一:适合需要对两列做差异化处理(比如不同的样式、单独的头部),或者需要严格控制每列数量的场景。
  • 方案二:适合简单的分列需求,代码量少,不用处理数组,缺点是如果模板项高度差异大,可能会出现列对齐不整齐的情况(用break-inside: avoid能缓解)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:38:16