Skip to content

Vue 分组 ​

通过 groupConfig 按字段分组展示数据,支持多级分组与展开/收起。

示例 ​

微应用尚未挂载。

源码 ​

点击查看源码
vue
<template>
  <div class="demo-wrapper">
    <h3 class="demo-title">Vue 分组</h3>
    <div class="virt-table-controls">
      <button
        type="button"
        class="virt-table-btn"
        style="background: #10b981; color: #fff"
        @click="expandAll"
      >
        全部展开
      </button>
      <button
        type="button"
        class="virt-table-btn"
        style="background: #6b7280; color: #fff"
        @click="collapseAll"
      >
        全部收起
      </button>
    </div>
    <div class="status-text">{{ status }}</div>
    <div style="width: 800px; height: 600px" class="demo-container">
      <VirtTableVue ref="tableRef" :columns="columns" :options="options" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { VirtTableVue, type VueTableColumn } from '@virt-table/vue';
import { faker } from '@faker-js/faker';
import type { VirtTableVueInstance } from '../../virt-table-ref';

type TableRef = VirtTableVueInstance & {
  expandAll: () => void;
  collapseAll: () => void;
};

const depts = ['工程部', '设计部', '市场部', '财务部'];
const teamNames = ['Alpha', 'Beta', 'Gamma'];
const groupRows = Array.from({ length: 200 }, (_, i) => ({
  id: i,
  name: faker.person.fullName(),
  department: depts[i % depts.length],
  team: teamNames[i % teamNames.length],
  score: Math.floor(Math.random() * 100),
}));

const columns: VueTableColumn[] = [
  { key: 'name', title: '姓名', width: 180 },
  { key: 'department', title: '部门', width: 120 },
  { key: 'team', title: '小组', width: 120 },
  { key: 'score', title: '分数', width: 100 },
];

const options = {
  list: groupRows,
  itemKey: 'id',
  estimatedSize: 40,
  buffer: 4,
  groupConfig: [{ field: 'department' }, { field: 'team' }],
  defaultExpandAll: true,
  border: true,
};

const tableRef = ref<TableRef | null>(null);
const status = ref('');

const expandAll = () => {
  tableRef.value?.expandAll();
  status.value = '全部展开';
};

const collapseAll = () => {
  tableRef.value?.collapseAll();
  status.value = '全部收起';
};

status.value = '分组:200 行';
</script>

分组行外观 ​

分组行会自动带上:左侧主色标记条、分组字段名(取同 key 列的 title)、分组值、条数徽标;整行可点击折叠/展开;横向滚动时分组标题会 sticky 停在左侧不被滚走。多级分组按层级(.vt-tr--group-lv1/2/3)自动递减底色与字号。

配色同样是变量,可单独覆盖:

css
.vt-root {
  --vt-group-bg: #eaf0fb; /* 分组行底色(默认由主色派生) */
  --vt-group-bg-lv2: #f1f5fd; /* 二级 */
  --vt-group-bg-lv3: #f6f9fe; /* 三级及更深 */
  --vt-group-bg-hover: #dfe9fa;
  --vt-group-border: #c9d8f2; /* 分组行上下分隔线 */
  --vt-group-accent: var(--vt-color-primary); /* 左侧标记条 */
  --vt-group-accent-width: 3px;
  --vt-group-text: var(--vt-text-color);
}

相关 API ​

字段 / 方法作用详见
groupConfig{ field, sort? }[],按字段层级分组表格配置
onGroupToggle / toggleFold折叠回调与编程控制实例方法
defaultExpandAll默认全部展开表格配置

分组行是整行接管(接管层),不进单元格内容链 —— 见渲染粒度。

全量字段见 表格配置 / 列配置 / 实例方法。

上面的字段在 Vue 端原样透传(实例方法通过组件 ref 调用)。封装层特有的部分 —— 组件 Props、渲染函数返回 VNode、ref 转发了哪些方法 —— 见 Vue API。