How to Use
Into the header. columns And data. DataSource To render.
Please provide a "key" for each data item in the dataSource that is different from the value of the other data items, or use the row Key parameter to specify an attribute name as the primary key, alternative row operation functions such as row selection and expansion of the table.
<script setup lang="ts">
import { Table } from '@fibrous/semi-ui-vue';
const columns = [
{
title: 'Title',
dataIndex: 'name',
},
{
title: 'Size',
dataIndex: 'size',
},
{
title: 'Owner',
dataIndex: 'owner',
},
{
title: 'Update',
dataIndex: 'updateTime',
},
];
const data = [
{
key: '1',
name: 'Semi Design design draft.fig',
size: '2M',
owner: 'Jiang Pengzhi',
updateTime: '2020-02-02 05:13',
},
{
key: '2',
name: 'Semi Design share docs',
size: '2M',
owner: 'Hao Xuan',
updateTime: '2020-01-17 05:31',
},
{
key: '3',
name: 'Design docs',
size: '34KB',
owner: 'Zoey Edwards',
updateTime: '2020-01-26 11:01',
},
];
</script>
<template>
<Table :columns="columns" :dataSource="data" :pagination="false" />
</template>
Demos
Basic Table
For tables, the two most basic parameters are dataSource and columns, the former is the data item, the latter is the configuration of each column, both are array types.
| 标题 | 大小 | 交付状态 | 所有者 | 更新日期 | |
|---|---|---|---|---|---|
| 2M | 已交付 | 姜 姜鹏志 | 2020-02-02 05:13 | ||
| 2M | 已延期 | 郝 郝宣 | 2020-01-17 05:31 | ||
| 34KB | 待评审 | Z Zoey Edwards | 2020-01-26 11:01 |
Code
<script setup lang="ts">
import { IconClear, IconComment, IconMore, IconTickCircle } from '@fibrous/semi-icons-vue';
import { Avatar, Table, Tag, type ColumnProps } from '@fibrous/semi-ui-vue';
interface Row {
key: string;
name: string;
nameIconSrc: string;
size: string;
owner: string;
status: 'success' | 'pending' | 'wait';
updateTime: string;
avatarBg: 'grey' | 'red' | 'light-blue';
}
const tagConfig = {
success: { color: 'green', icon: IconTickCircle, text: '已交付' },
pending: { color: 'pink', icon: IconClear, text: '已延期' },
wait: { color: 'cyan', icon: IconComment, text: '待评审' },
} as const;
const columns: ColumnProps<Row>[] = [
{
title: '标题',
dataIndex: 'name',
},
{
title: '大小',
dataIndex: 'size',
},
{
title: '交付状态',
dataIndex: 'status',
},
{
title: '所有者',
dataIndex: 'owner',
},
{
title: '更新日期',
dataIndex: 'updateTime',
},
{
title: '',
dataIndex: 'operate',
},
];
const data: Row[] = [
{
key: '1',
name: 'Semi Design 设计稿.fig',
nameIconSrc: '/assets/placeholder/app.svg',
size: '2M',
owner: '姜鹏志',
status: 'success',
updateTime: '2020-02-02 05:13',
avatarBg: 'grey',
},
{
key: '2',
name: 'Semi Design 分享演示文稿',
nameIconSrc: '/assets/docs-icon.png',
size: '2M',
owner: '郝宣',
status: 'pending',
updateTime: '2020-01-17 05:31',
avatarBg: 'red',
},
{
key: '3',
name: '设计文档',
nameIconSrc: '/assets/docs-icon.png',
size: '34KB',
status: 'wait',
owner: 'Zoey Edwards',
updateTime: '2020-01-26 11:01',
avatarBg: 'light-blue',
},
];
</script>
<template>
<Table :columns="columns" :dataSource="data" :pagination="false">
<template #cell="{ column, record, text }">
<div v-if="column.dataIndex === 'name'">
<Avatar alt="" shape="square" size="small" :src="record.nameIconSrc" :style="{ marginRight: '12px' }" />
{{ text }}
</div>
<Tag v-else-if="column.dataIndex === 'status'" :color="tagConfig[text as Row['status']].color" shape="circle" :style="{ userSelect: 'text' }">
<template #prefixIcon>
<component :is="tagConfig[text as Row['status']].icon" />
</template>
{{ tagConfig[text as Row['status']].text }}
</Tag>
<div v-else-if="column.dataIndex === 'owner'">
<Avatar :color="record.avatarBg" size="small" :style="{ marginRight: '4px' }">
{{ typeof text === 'string' && text.slice(0, 1) }}
</Avatar>
{{ text }}
</div>
<IconMore v-else-if="column.dataIndex === 'operate'" />
</template>
</Table>
</template>Table.Column Writing
You can also define columns by writing Table.Column as children of Table: the column data goes on its props, and the custom content of cells and titles goes in its #cell, #title and other slots. Table only reads direct children, so you cannot wrap Table.Column in any other component; direct children produced by v-if and v-for are fine.
| 标题 | 大小 | 所有者 | 更新时间 | |
|---|---|---|---|---|
| 2M | 姜 姜鹏志 | 2020-02-02 05:13 | ||
| 2M | 郝 郝宣 | 2020-01-17 05:31 | ||
| 34KB | Z Zoey Edwards | 2020-01-26 11:01 |
Code
<script setup lang="ts">
import { IconMore } from '@fibrous/semi-icons-vue';
import { Avatar, Table, TableColumn as Column, type AvatarProps } from '@fibrous/semi-ui-vue';
interface Row {
key: string;
name: string;
nameIconSrc: string;
size: string;
owner: string;
status: string;
updateTime: string;
avatarBg: AvatarProps['color'];
}
const data: Row[] = [
{
key: '1',
name: 'Semi Design 设计稿.fig',
nameIconSrc: '/assets/placeholder/app.svg',
size: '2M',
owner: '姜鹏志',
status: 'success',
updateTime: '2020-02-02 05:13',
avatarBg: 'grey',
},
{
key: '2',
name: 'Semi Design 分享演示文稿',
nameIconSrc: '/assets/docs-icon.png',
size: '2M',
owner: '郝宣',
status: 'pending',
updateTime: '2020-01-17 05:31',
avatarBg: 'red',
},
{
key: '3',
name: '设计文档',
nameIconSrc: '/assets/docs-icon.png',
size: '34KB',
status: 'wait',
owner: 'Zoey Edwards',
updateTime: '2020-01-26 11:01',
avatarBg: 'light-blue',
},
];
</script>
<template>
<Table :dataSource="data" :pagination="false">
<Column key="name" dataIndex="name" title="标题">
<template #cell="{ text, record }">
<div>
<Avatar alt="" shape="square" size="small" :src="record.nameIconSrc" :style="{ marginRight: '12px' }" />
{{ text }}
</div>
</template>
</Column>
<Column key="size" dataIndex="size" title="大小" />
<Column key="owner" dataIndex="owner" title="所有者">
<template #cell="{ text, record }">
<div>
<Avatar :color="record.avatarBg" size="small" :style="{ marginRight: '4px' }">
{{ typeof text === 'string' && text.slice(0, 1) }}
</Avatar>
{{ text }}
</div>
</template>
</Column>
<Column key="updateTime" dataIndex="updateTime" title="更新时间" />
<Column key="operate" dataIndex="operate" title="">
<template #cell>
<IconMore />
</template>
</Column>
</Table>
</template>Row Selection Operation
This feature can be turned on by passing in rowSelection.
- Click the selection box in the header, and all rows in the
dataSourcethat are not in the state ofdisabledwill be selected. The callback function for selecting all rows isonSelectAll; - Clicking on the row selection box will select the current row. Its callback function is
onSelect;
| 标题 | 大小 | 交付状态 | 所有者 | 更新日期 | ||
|---|---|---|---|---|---|---|
| 2M | 已交付 | 姜 姜鹏志 | 2020-02-02 05:13 | |||
| 2M | 已延期 | 郝 郝宣 | 2020-01-17 05:31 | |||
| 34KB | 待评审 | Z Zoey Edwards | 2020-01-26 11:01 |
Code
<script setup lang="ts">
import { IconClear, IconComment, IconMore, IconTickCircle } from '@fibrous/semi-icons-vue';
import { Avatar, Table, Tag, type ColumnProps, type RowSelectionProps } from '@fibrous/semi-ui-vue';
interface Row {
key: string;
name: string;
nameIconSrc: string;
size: string;
owner: string;
status: 'success' | 'pending' | 'wait';
updateTime: string;
avatarBg: 'grey' | 'red' | 'light-blue';
}
const tagConfig = {
success: { color: 'green', icon: IconTickCircle, text: '已交付' },
pending: { color: 'pink', icon: IconClear, text: '已延期' },
wait: { color: 'cyan', icon: IconComment, text: '待评审' },
} as const;
const columns: ColumnProps<Row>[] = [
{
title: '标题',
dataIndex: 'name',
width: 400,
},
{
title: '大小',
dataIndex: 'size',
},
{
title: '交付状态',
dataIndex: 'status',
},
{
title: '所有者',
dataIndex: 'owner',
},
{
title: '更新日期',
dataIndex: 'updateTime',
},
{
title: '',
dataIndex: 'operate',
},
];
const data: Row[] = [
{
key: '1',
name: 'Semi Design 设计稿.fig',
nameIconSrc: '/assets/placeholder/app.svg',
size: '2M',
owner: '姜鹏志',
status: 'success',
updateTime: '2020-02-02 05:13',
avatarBg: 'grey',
},
{
key: '2',
name: 'Semi Design 分享演示文稿',
nameIconSrc: '/assets/docs-icon.png',
size: '2M',
owner: '郝宣',
status: 'pending',
updateTime: '2020-01-17 05:31',
avatarBg: 'red',
},
{
key: '3',
name: '设计文档',
nameIconSrc: '/assets/docs-icon.png',
size: '34KB',
status: 'wait',
owner: 'Zoey Edwards',
updateTime: '2020-01-26 11:01',
avatarBg: 'light-blue',
},
{
key: '4',
name: 'Semi D2C 设计稿.fig',
nameIconSrc: '/assets/placeholder/app.svg',
size: '2M',
owner: '姜鹏志',
status: 'wait',
updateTime: '2020-02-02 05:13',
avatarBg: 'grey',
},
{
key: '5',
name: 'Semi D2C 分享演示文稿',
nameIconSrc: '/assets/docs-icon.png',
size: '2M',
owner: '郝宣',
status: 'pending',
updateTime: '2020-01-17 05:31',
avatarBg: 'red',
},
{
key: '6',
name: 'Semi D2C 设计文档',
nameIconSrc: '/assets/docs-icon.png',
size: '34KB',
status: 'success',
owner: 'Zoey Edwards',
updateTime: '2020-01-26 11:01',
avatarBg: 'light-blue',
},
];
const rowSelection: RowSelectionProps<Row> = {
getCheckboxProps: (record) => ({
disabled: record.name === '设计文档', // 这一行不可勾选
name: record.name,
}),
onSelect: (record, selected) => {
console.log(`select row: ${selected}`, record);
},
onSelectAll: (selected, selectedRows) => {
console.log(`select all rows: ${selected}`, selectedRows);
},
onChange: (selectedRowKeys, selectedRows) => {
console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
},
};
const pagination = { pageSize: 3 };
</script>
<template>
<Table :columns="columns" :dataSource="data" :pagination="pagination" :rowSelection="rowSelection">
<template #cell="{ column, record, text }">
<div v-if="column.dataIndex === 'name'">
<Avatar alt="" shape="square" size="small" :src="record.nameIconSrc" :style="{ marginRight: '12px' }" />
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'size'">{{ text }}</template>
<Tag v-else-if="column.dataIndex === 'status'" :color="tagConfig[text as Row['status']].color" shape="circle" :style="{ userSelect: 'text' }">
<template #prefixIcon>
<component :is="tagConfig[text as Row['status']].icon" />
</template>
{{ tagConfig[text as Row['status']].text }}
</Tag>
<div v-else-if="column.dataIndex === 'owner'">
<Avatar :color="record.avatarBg" size="small" :style="{ marginRight: '4px' }">
{{ typeof text === 'string' && text.slice(0, 1) }}
</Avatar>
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'updateTime'">{{ text }}</template>
<IconMore v-else-if="column.dataIndex === 'operate'" />
</template>
</Table>
</template>Custom Rendering
Users can use the #cell scoped slot to customize the rendering of cells, which is suitable for rendering more complex cell content. The #cell slot on Table is called for every data column; tell the columns apart with column.dataIndex or column.key. When the slot outputs nothing, the raw value is shown. To customize one column only, put #cell on that column's Table.Column instead, which takes precedence over the slot on Table.
The parameter of #cell is an object containing the following properties:
text: the value atcolumn.dataIndex, or the data item itself for a column withoutdataIndexrecord: the data item of the current rowindex: the index of the data item among its siblingscolumn: the configuration of the current columnexpandIcon: Expand icon (when using tree data or expandable rows)isHovering: Whether the current row is in hover stateselection,indentText: the selection checkbox and the indent content, provided only when the column enablesuseFullRender, see Fully custom rendering
With the isHovering parameter, you can implement interaction effects such as displaying action buttons on mouse hover.
| 标题 | 大小 | 交付状态 | 所有者 | 更新日期 | |
|---|---|---|---|---|---|
| 2M | 已交付 | 姜 姜鹏志 | 2020-02-02 05:13 | ||
| 2M | 已延期 | 郝 郝宣 | 2020-01-17 05:31 | ||
| 34KB | 待评审 | Z Zoey Edwards | 2020-01-26 11:01 | ||
| 34KB | 已交付 | 姜 姜琪 | 2020-01-26 11:01 |
Code
<script setup lang="ts">
import { shallowRef } from 'vue';
import { IconClear, IconComment, IconDelete, IconTickCircle } from '@fibrous/semi-icons-vue';
import { IllustrationNoResult, IllustrationNoResultDark } from '@fibrous/semi-illustrations-vue';
import { Avatar, Button, Empty, Table, Tag, Typography, type ColumnProps } from '@fibrous/semi-ui-vue';
const { Text } = Typography;
interface Row {
key: string;
name: string;
nameIconSrc: string;
size: string;
owner: string;
status: 'success' | 'pending' | 'wait';
updateTime: string;
avatarBg: 'grey' | 'red' | 'light-blue' | 'green';
}
const tagConfig = {
success: { color: 'green', icon: IconTickCircle, text: '已交付' },
pending: { color: 'pink', icon: IconClear, text: '已延期' },
wait: { color: 'cyan', icon: IconComment, text: '待评审' },
} as const;
const raw: Row[] = [
{
key: '1',
name: 'Semi Design 设计稿标题可能有点长这时候应该显示 Tooltip.fig',
nameIconSrc: '/assets/placeholder/app.svg',
size: '2M',
owner: '姜鹏志',
status: 'success',
updateTime: '2020-02-02 05:13',
avatarBg: 'grey',
},
{
key: '2',
name: 'Semi Design 分享演示文稿',
nameIconSrc: '/assets/docs-icon.png',
size: '2M',
owner: '郝宣',
status: 'pending',
updateTime: '2020-01-17 05:31',
avatarBg: 'red',
},
{
key: '3',
name: '设计文档',
nameIconSrc: '/assets/docs-icon.png',
size: '34KB',
status: 'wait',
owner: 'Zoey Edwards',
updateTime: '2020-01-26 11:01',
avatarBg: 'light-blue',
},
{
key: '4',
name: 'Semi D2C 设计文档可能也有点长所以也会显示 Tooltip',
nameIconSrc: '/assets/docs-icon.png',
size: '34KB',
status: 'success',
owner: '姜琪',
updateTime: '2020-01-26 11:01',
avatarBg: 'green',
},
];
const dataSource = shallowRef(raw);
const removeRecord = (key: string) => {
dataSource.value = dataSource.value.filter((data) => data.key !== key);
};
const resetData = () => {
dataSource.value = [...raw];
};
const columns: ColumnProps<Row>[] = [
{
title: '标题',
dataIndex: 'name',
width: 400,
},
{
title: '大小',
dataIndex: 'size',
width: 150,
},
{
title: '交付状态',
dataIndex: 'status',
},
{
title: '所有者',
dataIndex: 'owner',
width: 300,
},
{
title: '更新日期',
dataIndex: 'updateTime',
width: 200,
},
{
title: '',
dataIndex: 'operate',
},
];
</script>
<template>
<div>
<Button :style="{ marginBottom: '10px' }" @click="resetData">重置</Button>
<Table :columns="columns" :dataSource="dataSource" :pagination="false" :style="{ minHeight: '350px' }">
<template #cell="{ column, record, text }">
<span v-if="column.dataIndex === 'name'" :style="{ display: 'flex', alignItems: 'center' }">
<Avatar alt="" shape="square" size="small" :src="record.nameIconSrc" :style="{ marginRight: '12px' }" />
<!-- Width = the cell's 400px minus the non-text content -->
<Text :ellipsis="{ showTooltip: true }" :style="{ width: 'calc(400px - 76px)' }">{{ text }}</Text>
</span>
<Tag v-else-if="column.dataIndex === 'status'" :color="tagConfig[text as Row['status']].color" shape="circle" :style="{ userSelect: 'text' }">
<template #prefixIcon>
<component :is="tagConfig[text as Row['status']].icon" />
</template>
{{ tagConfig[text as Row['status']].text }}
</Tag>
<div v-else-if="column.dataIndex === 'owner'">
<Avatar :color="record.avatarBg" size="small" :style="{ marginRight: '4px' }">
{{ typeof text === 'string' && text.slice(0, 1) }}
</Avatar>
{{ text }}
</div>
<Button v-else-if="column.dataIndex === 'operate'" aria-label="删除" theme="borderless" @click="removeRecord(record.key)">
<template #icon>
<IconDelete />
</template>
</Button>
</template>
<template #empty>
<Empty>
<template #image>
<IllustrationNoResult />
</template>
<template #darkModeImage>
<IllustrationNoResultDark />
</template>
<template #description>搜索无结果</template>
</Empty>
</template>
</Table>
</div>
</template>Table With Pagination
Table paging currently supports two modes: controlled and uncontrolled.
- In controlled mode, the paging state is passed entirely externally, depending on whether the pagination .currentPage field is passed. In general, the controlled mode is suitable for remotely pulling data and rendering.
- In uncontrolled mode, Table passes the incoming dataSource length as total to the Pagination component by default, and of course you can also pass a total field to overwrite the value of the Table component, but we do not recommend users to pass this field in uncontrolled paging mode.
Note: The custom
pagination.totalfield passed in uncontrolled conditions is supported.
标题 | 交付状态 | 所有者 |
|---|
| 0 KB | 已交付 | 姜 姜鹏志 | 2024-05-06 | ||
| 5 KB | 待评审 | 郝 郝宣 | 2024-05-11 | ||
| 10 KB | 已交付 | 姜 姜鹏志 | 2024-05-16 | ||
| 15 KB | 待评审 | 郝 郝宣 | 2024-05-21 | ||
| 20 KB | 已交付 | 姜 姜鹏志 | 2024-05-26 | ||
| 25 KB | 待评审 | 郝 郝宣 | 2024-05-31 | ||
| 30 KB | 已交付 | 姜 姜鹏志 | 2024-06-05 | ||
| 35 KB | 待评审 | 郝 郝宣 | 2024-06-10 | ||
| 40 KB | 已交付 | 姜 姜鹏志 | 2024-06-15 | ||
| 45 KB | 待评审 | 郝 郝宣 | 2024-06-20 |
Code
<script setup lang="ts">
import * as dateFns from 'date-fns';
import { IconClear, IconComment, IconTickCircle } from '@fibrous/semi-icons-vue';
import { Avatar, Table, Tag, type ColumnProps, type RowSelectionProps } from '@fibrous/semi-ui-vue';
const figmaIconUrl = '/assets/placeholder/app.svg';
interface Row {
key: string;
name: string;
owner: string;
size: number;
status: 'success' | 'wait';
updateTime: number;
avatarBg: 'grey' | 'red';
}
const columns: ColumnProps<Row>[] = [
{
title: '标题',
dataIndex: 'name',
width: 400,
filters: [
{
text: 'Semi Design 设计稿',
value: 'Semi Design 设计稿',
},
{
text: 'Semi D2C 设计稿',
value: 'Semi D2C 设计稿',
},
],
onFilter: (value, record) => record.name.includes(value),
},
{
title: '大小',
dataIndex: 'size',
sorter: (a, b) => (a.size - b.size > 0 ? 1 : -1),
},
{
title: '交付状态',
dataIndex: 'status',
},
{
title: '所有者',
dataIndex: 'owner',
},
{
title: '更新日期',
dataIndex: 'updateTime',
sorter: (a, b) => (a.updateTime - b.updateTime > 0 ? 1 : -1),
},
];
const tagConfig = {
success: { color: 'green', icon: IconTickCircle, text: '已交付' },
pending: { color: 'pink', icon: IconClear, text: '已延期' },
wait: { color: 'cyan', icon: IconComment, text: '待评审' },
} as const;
const getTag = (status: keyof typeof tagConfig) => tagConfig[status];
const DAY = 24 * 60 * 60 * 1000;
const getData = () => {
const data: Row[] = [];
for (let i = 0; i < 46; i++) {
const isSemiDesign = i % 2 === 0;
const randomNumber = (i * 1000) % 199;
data.push({
key: '' + i,
name: isSemiDesign ? `Semi Design 设计稿${i}.fig` : `Semi D2C 设计稿${i}.fig`,
owner: isSemiDesign ? '姜鹏志' : '郝宣',
size: randomNumber,
status: isSemiDesign ? 'success' : 'wait',
updateTime: new Date(2024, 4, 6, 12).valueOf() + randomNumber * DAY,
avatarBg: isSemiDesign ? 'grey' : 'red',
});
}
return data;
};
const dataSource = getData();
const rowSelection: RowSelectionProps<Row> = {
onChange: (selectedRowKeys, selectedRows) => {
console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
},
getCheckboxProps: (record) => ({
disabled: record.name === 'Semi Design 设计稿0.fig', // 这一行不可勾选
name: record.name,
}),
};
const scroll = { y: 300 };
</script>
<template>
<Table :columns="columns" :dataSource="dataSource" :rowSelection="rowSelection" :scroll="scroll">
<template #cell="{ column, text, record }">
<div v-if="column.dataIndex === 'name'">
<Avatar alt="" shape="square" size="small" :src="figmaIconUrl" :style="{ marginRight: '12px' }" />
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'size'">{{ text }} KB</template>
<Tag v-else-if="column.dataIndex === 'status'" :color="getTag(text).color" shape="circle" :style="{ userSelect: 'text' }">
<template #prefixIcon>
<component :is="getTag(text).icon" />
</template>
{{ getTag(text).text }}
</Tag>
<div v-else-if="column.dataIndex === 'owner'">
<Avatar :color="record.avatarBg" size="small" :style="{ marginRight: '4px' }">
{{ typeof text === 'string' && text.slice(0, 1) }}
</Avatar>
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'updateTime'">
{{ dateFns.format(new Date(text), 'yyyy-MM-dd') }}
</template>
</template>
</Table>
</template>Pull Remote Data
Under normal circumstances, the data is often not obtained at one time. We will retrieve the data from the interface when clicking on the page number, filter or sort button. In this case, please use Controlled mode To handle pagination. The user needs to pass in the pagination.currentPage field, where the rendering of the pagination component depends entirely on the incoming pagination object.
标题 | 交付状态 | 所有者 |
|---|
Code
<script setup lang="ts">
import { ref, watch } from 'vue';
import * as dateFns from 'date-fns';
import { IconClear, IconComment, IconTickCircle } from '@fibrous/semi-icons-vue';
import { Avatar, Table, Tag, type ColumnProps } from '@fibrous/semi-ui-vue';
const DAY = 24 * 60 * 60 * 1000;
const figmaIconUrl = '/assets/placeholder/app.svg';
const pageSize = 5;
interface Row {
key: string;
name: string;
owner: string;
size: number;
status: 'success' | 'wait';
updateTime: number;
avatarBg: 'grey' | 'red';
}
const tagConfig = {
success: { color: 'green', icon: IconTickCircle, text: '已交付' },
pending: { color: 'pink', icon: IconClear, text: '已延期' },
wait: { color: 'cyan', icon: IconComment, text: '待评审' },
} as const;
const columns: ColumnProps<Row>[] = [
{
title: '标题',
dataIndex: 'name',
width: 400,
filters: [
{
text: 'Semi Design 设计稿',
value: 'Semi Design 设计稿',
},
{
text: 'Semi D2C 设计稿',
value: 'Semi D2C 设计稿',
},
],
onFilter: (value, record) => record.name.includes(value),
},
{
title: '大小',
dataIndex: 'size',
sorter: (a, b) => (a.size - b.size > 0 ? 1 : -1),
},
{
title: '交付状态',
dataIndex: 'status',
},
{
title: '所有者',
dataIndex: 'owner',
},
{
title: '更新日期',
dataIndex: 'updateTime',
sorter: (a, b) => (a.updateTime - b.updateTime > 0 ? 1 : -1),
},
];
const getData = () => {
const data: Row[] = [];
for (let i = 0; i < 46; i++) {
const isSemiDesign = i % 2 === 0;
const randomNumber = (i * 1000) % 199;
data.push({
key: '' + i,
name: isSemiDesign ? `Semi Design 设计稿${i}.fig` : `Semi D2C 设计稿${i}.fig`,
owner: isSemiDesign ? '姜鹏志' : '郝宣',
size: randomNumber,
status: isSemiDesign ? 'success' : 'wait',
updateTime: new Date(2024, 4, 6, 12).valueOf() + randomNumber * DAY,
avatarBg: isSemiDesign ? 'grey' : 'red',
});
}
return data;
};
const data = getData();
const fetchData = (currentPage: number) => {
return new Promise<Row[]>((res) => {
setTimeout(() => {
res(data.slice((currentPage - 1) * pageSize, currentPage * pageSize));
}, 300);
});
};
const dataSource = ref<Row[]>([]);
const loading = ref(true);
const currentPage = ref(1);
const handlePageChange = (page: number) => {
loading.value = true;
currentPage.value = page;
};
watch(
currentPage,
(page, _prev, onCleanup) => {
// Drop responses for pages the user has left
let ignore = false;
onCleanup(() => {
ignore = true;
});
void fetchData(page).then((rows) => {
if (!ignore) {
loading.value = false;
dataSource.value = rows;
}
});
},
{ immediate: true }
);
</script>
<template>
<Table :columns="columns" :dataSource="dataSource" :loading="loading" :pagination="{ currentPage, pageSize, total: data.length, onPageChange: handlePageChange }">
<template #cell="{ column, record, text }">
<div v-if="column.dataIndex === 'name'">
<Avatar alt="" shape="square" size="small" :src="figmaIconUrl" :style="{ marginRight: '12px' }" />
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'size'">{{ text }} KB</template>
<Tag v-else-if="column.dataIndex === 'status'" :color="tagConfig[text as Row['status']].color" shape="circle" :style="{ userSelect: 'text' }">
<template #prefixIcon>
<component :is="tagConfig[text as Row['status']].icon" />
</template>
{{ tagConfig[text as Row['status']].text }}
</Tag>
<div v-else-if="column.dataIndex === 'owner'">
<Avatar :color="record.avatarBg" size="small" :style="{ marginRight: '4px' }">
{{ typeof text === 'string' && text.slice(0, 1) }}
</Avatar>
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'updateTime'">
{{ dateFns.format(new Date(text), 'yyyy-MM-dd') }}
</template>
</template>
</Table>
</template>Fixed Column or Head
You can fix the column by setting the Fixed attribute of the column and scroll.x, and fix the header by setting scroll.y.
- It is recommended to specify scroll.x as a fixed value or percentage greater than the width of the table. If it is a fixed value, set it to >= the sum of all fixed column widths + the sum of all table column widths.
- Make sure that all elements inside the table do not affect the height of the cells after rendering (e.g. containing unloaded pictures, etc.). In this case, give the stator element a definite height to ensure that the left and right Fixed columns of cells are not deranged.
- If the column header is not aligned with the content or there is a column duplication or when the fixed column fails, specify the width width of the fixed column, if still not effective, try to recommend leaving a column with no width to accommodate the elastic layout, or check for ultra-long continuous fields to destroy the layout.
标题 | 所有者 |
|---|
| 0 KB | 姜 姜鹏志 | 2024-05-06 | |||
| 5 KB | 郝 郝宣 | 2024-05-11 | |||
| 10 KB | 姜 姜鹏志 | 2024-05-16 | |||
| 15 KB | 郝 郝宣 | 2024-05-21 | |||
| 20 KB | 姜 姜鹏志 | 2024-05-26 | |||
| 25 KB | 郝 郝宣 | 2024-05-31 | |||
| 30 KB | 姜 姜鹏志 | 2024-06-05 | |||
| 35 KB | 郝 郝宣 | 2024-06-10 | |||
| 40 KB | 姜 姜鹏志 | 2024-06-15 | |||
| 45 KB | 郝 郝宣 | 2024-06-20 |
Code
<script setup lang="ts">
import * as dateFns from 'date-fns';
import { IconMore } from '@fibrous/semi-icons-vue';
import { Avatar, Table, type ColumnProps, type RowSelectionProps } from '@fibrous/semi-ui-vue';
const DAY = 24 * 60 * 60 * 1000;
const figmaIconUrl = '/assets/placeholder/app.svg';
interface Row {
key: string;
name: string;
owner: string;
size: number;
updateTime: number;
avatarBg: 'grey' | 'red';
}
const columns: ColumnProps<Row>[] = [
{
title: '标题',
dataIndex: 'name',
fixed: true,
width: 250,
filters: [
{
text: 'Semi Design 设计稿',
value: 'Semi Design 设计稿',
},
{
text: 'Semi D2C 设计稿',
value: 'Semi D2C 设计稿',
},
],
onFilter: (value, record) => record.name.includes(value),
},
{
title: '大小',
dataIndex: 'size',
width: 200,
sorter: (a, b) => (a.size - b.size > 0 ? 1 : -1),
},
{
title: '所有者',
dataIndex: 'owner',
width: 200,
},
{
title: '更新日期',
dataIndex: 'updateTime',
width: 200,
sorter: (a, b) => (a.updateTime - b.updateTime > 0 ? 1 : -1),
},
{
title: '',
dataIndex: 'operate',
fixed: 'right',
align: 'center',
width: 100,
},
];
const getData = () => {
const data: Row[] = [];
for (let i = 0; i < 46; i++) {
const isSemiDesign = i % 2 === 0;
const randomNumber = (i * 1000) % 199;
data.push({
key: '' + i,
name: isSemiDesign ? `Semi Design 设计稿${i}.fig` : `Semi D2C 设计稿${i}.fig`,
owner: isSemiDesign ? '姜鹏志' : '郝宣',
size: randomNumber,
updateTime: new Date(2024, 4, 6, 12).valueOf() + randomNumber * DAY,
avatarBg: isSemiDesign ? 'grey' : 'red',
});
}
return data;
};
const dataSource = getData();
const scroll = { y: 300, x: 1200 };
const rowSelection: RowSelectionProps<Row> = {
onChange: (selectedRowKeys, selectedRows) => {
console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
},
getCheckboxProps: (record) => ({
disabled: record.name === 'Semi Design 设计稿0.fig', // 这一行不可勾选
name: record.name,
}),
fixed: true,
};
</script>
<template>
<Table :columns="columns" :dataSource="dataSource" :rowSelection="rowSelection" :scroll="scroll">
<template #cell="{ column, text, record }">
<div v-if="column.dataIndex === 'name'">
<Avatar alt="" shape="square" size="small" :src="figmaIconUrl" :style="{ marginRight: '12px' }" />
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'size'">{{ text }} KB</template>
<div v-else-if="column.dataIndex === 'owner'">
<Avatar :color="record.avatarBg" size="small" :style="{ marginRight: '4px' }">
{{ text.slice(0, 1) }}
</Avatar>
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'updateTime'">
{{ dateFns.format(new Date(text), 'yyyy-MM-dd') }}
</template>
<IconMore v-else-if="column.dataIndex === 'operate'" />
</template>
</Table>
</template>The header can be fixed to the top of the page with the sticky property. When passing top, you can control the distance from the scroll container.
After turning on sticky, Table will automatically turn on the fixed layout, and the column width will be determined by column.width. Columns without a given width are automatically assigned by the browser.
<script setup lang="ts">
import { onMounted, shallowRef } from 'vue';
import * as dateFns from 'date-fns';
import { IconMore } from '@fibrous/semi-icons-vue';
import { Avatar, Table } from '@fibrous/semi-ui-vue';
import type { ColumnProps, RowSelectionProps } from '@fibrous/semi-ui-vue';
interface Row {
key: string;
name: string;
owner: string;
size: number;
updateTime: number;
avatarBg: 'grey' | 'red';
}
const DAY = 24 * 60 * 60 * 1000;
const figmaIconUrl = '/assets/placeholder/app.svg';
const columns: ColumnProps<Row>[] = [
{
title: 'Title',
dataIndex: 'name',
fixed: true,
width: 250,
filters: [
{
text: 'Semi Design draft',
value: 'Semi Design',
},
{
text: 'Semi D2C draft',
value: 'Semi D2C',
},
],
onFilter: (value, record) => record.name.includes(value),
},
{
title: 'Size',
dataIndex: 'size',
width: 200,
sorter: (a, b) => (a.size - b.size > 0 ? 1 : -1),
},
{
title: 'Owner',
dataIndex: 'owner',
width: 200,
},
{
title: 'Update',
dataIndex: 'updateTime',
width: 200,
sorter: (a, b) => (a.updateTime - b.updateTime > 0 ? 1 : -1),
},
{
title: '',
dataIndex: 'operate',
fixed: 'right',
align: 'center',
width: 100,
},
];
const dataSource = shallowRef<Row[]>([]);
const scroll = { y: 300, x: 1200 };
const sticky = { top: 60 };
const rowSelection: RowSelectionProps<Row> = {
onChange: (selectedRowKeys, selectedRows) => {
console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
},
getCheckboxProps: (record) => ({
disabled: record.name === 'Michael James', // This row cannot be checked
name: record.name,
}),
fixed: true,
};
onMounted(() => {
const data: Row[] = [];
for (let i = 0; i < 46; i++) {
const isSemiDesign = i % 2 === 0;
const randomNumber = (i * 1000) % 199;
data.push({
key: '' + i,
name: isSemiDesign ? `Semi Design draft ${i}.fig` : `Semi D2C draft ${i}.fig`,
owner: isSemiDesign ? 'Jiang Pengzhi' : 'Hao Xuan',
size: randomNumber,
updateTime: new Date().valueOf() + randomNumber * DAY,
avatarBg: isSemiDesign ? 'grey' : 'red',
});
}
dataSource.value = data;
});
</script>
<template>
<Table :columns="columns" :dataSource="dataSource" :rowSelection="rowSelection" :scroll="scroll" :sticky="sticky">
<template #cell="{ column, record, text }">
<div v-if="column.dataIndex === 'name'">
<Avatar alt="" shape="square" size="small" :src="figmaIconUrl" :style="{ marginRight: '12px' }" />
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'size'">{{ text }} KB</template>
<div v-else-if="column.dataIndex === 'owner'">
<Avatar :color="record.avatarBg" size="small" :style="{ marginRight: '4px' }">
{{ typeof text === 'string' && text.slice(0, 1) }}
</Avatar>
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'updateTime'">
{{ dateFns.format(new Date(text), 'yyyy-MM-dd') }}
</template>
<IconMore v-else-if="column.dataIndex === 'operate'" />
</template>
</Table>
</template>
Table Header With Sorting and Filtering Function
Filters and sorting controls are integrated inside the table, and users can pass in the sorter display of the sorter open header by passing filters in Column and the filter control display of the onFilter open header.
Note: Be sure to provide a "key" for each row of data that is different from other row values, or use the rowKey parameter to specify a property name as the primary key.
Note: Sorting and filtering columns must set independent "dataIndex"
| 交付状态 | 所有者 |
|---|
| 0 KB | 已交付 | 姜 姜鹏志 | 2024-05-06 | ||
| 5 KB | 待评审 | 郝 郝宣 | 2024-05-11 | ||
| 10 KB | 已交付 | 姜 姜鹏志 | 2024-05-16 | ||
| 15 KB | 待评审 | 郝 郝宣 | 2024-05-21 | ||
| 20 KB | 已交付 | 姜 姜鹏志 | 2024-05-26 | ||
| 25 KB | 待评审 | 郝 郝宣 | 2024-05-31 | ||
| 30 KB | 已交付 | 姜 姜鹏志 | 2024-06-05 | ||
| 35 KB | 待评审 | 郝 郝宣 | 2024-06-10 | ||
| 40 KB | 已交付 | 姜 姜鹏志 | 2024-06-15 | ||
| 45 KB | 待评审 | 郝 郝宣 | 2024-06-20 |
Code
<script setup lang="ts">
import * as dateFns from 'date-fns';
import { IconClear, IconComment, IconTickCircle } from '@fibrous/semi-icons-vue';
import { Avatar, Table, Tag, type ColumnProps, type RowSelectionProps } from '@fibrous/semi-ui-vue';
const DAY = 24 * 60 * 60 * 1000;
const figmaIconUrl = '/assets/placeholder/app.svg';
interface Row {
key: string;
name: string;
owner: string;
size: number;
status: 'success' | 'wait';
updateTime: number;
avatarBg: 'grey' | 'red';
}
const tagConfig = {
success: { color: 'green', icon: IconTickCircle, text: '已交付' },
pending: { color: 'pink', icon: IconClear, text: '已延期' },
wait: { color: 'cyan', icon: IconComment, text: '待评审' },
} as const;
const columns: ColumnProps<Row>[] = [
{
title: '标题',
dataIndex: 'name',
width: 400,
filters: [
{
text: 'Semi Design 设计稿',
value: 'Semi Design 设计稿',
},
{
text: 'Semi D2C 设计稿',
value: 'Semi D2C 设计稿',
},
],
onFilter: (value, record) => record.name.includes(value),
sorter: (a, b) => (a.name.length - b.name.length > 0 ? 1 : -1),
},
{
title: '大小',
dataIndex: 'size',
sorter: (a, b) => (a.size - b.size > 0 ? 1 : -1),
},
{
title: '交付状态',
dataIndex: 'status',
},
{
title: '所有者',
dataIndex: 'owner',
},
{
title: '更新日期',
dataIndex: 'updateTime',
sorter: (a, b) => (a.updateTime - b.updateTime > 0 ? 1 : -1),
},
];
const dataSource: Row[] = [];
for (let i = 0; i < 46; i++) {
const isSemiDesign = i % 2 === 0;
const randomNumber = (i * 1000) % 199;
dataSource.push({
key: '' + i,
name: isSemiDesign ? `Semi Design 设计稿${i}.fig` : `Semi D2C 设计稿${i}.fig`,
owner: isSemiDesign ? '姜鹏志' : '郝宣',
size: randomNumber,
status: isSemiDesign ? 'success' : 'wait',
updateTime: new Date(2024, 4, 6, 12).valueOf() + randomNumber * DAY,
avatarBg: isSemiDesign ? 'grey' : 'red',
});
}
const rowSelection: RowSelectionProps<Row> = {
onChange: (selectedRowKeys, selectedRows) => {
console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
},
getCheckboxProps: (record) => ({
disabled: record.name === 'Semi Design 设计稿0.fig', // 这一行不可勾选
name: record.name,
}),
};
const scroll = { y: 300 };
</script>
<template>
<Table :columns="columns" :dataSource="dataSource" :rowSelection="rowSelection" :scroll="scroll">
<template #cell="{ column, record, text }">
<div v-if="column.dataIndex === 'name'">
<Avatar alt="" shape="square" size="small" :src="figmaIconUrl" :style="{ marginRight: '12px' }" />
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'size'">{{ text }} KB</template>
<Tag v-else-if="column.dataIndex === 'status'" :color="tagConfig[text as Row['status']].color" shape="circle" :style="{ userSelect: 'text' }">
<template #prefixIcon>
<component :is="tagConfig[text as Row['status']].icon" />
</template>
{{ tagConfig[text as Row['status']].text }}
</Tag>
<div v-else-if="column.dataIndex === 'owner'">
<Avatar :color="record.avatarBg" size="small" :style="{ marginRight: '4px' }">
{{ typeof text === 'string' && text.slice(0, 1) }}
</Avatar>
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'updateTime'">
{{ dateFns.format(new Date(text), 'yyyy-MM-dd') }}
</template>
</template>
</Table>
</template>When sorter is a function type, the sortOrder status can be obtained through the third parameter of the function. The function type is (a?: RecordType, b?: RecordType, sortOrder?: 'ascend' | 'descend') => number.
You can control whether to display the sorting tip through the showSortTip attribute, which defaults to false. When the tip is turned on, when there is only sorting function, the sorting prompt will be displayed when the mouse is moved to the table header; in other cases, the sorting prompt will be displayed only when the mouse is moved to the sorting icon.
Note: When using the sortOrder attribute for controlled sorting, since the next sort order cannot be predicted, showSortTip does not take effect and the prompt will not be displayed.
| 标题 | 所有者 | 更新日期 | |
|---|---|---|---|
| 3 KB | 姜 姜鹏志 | 2020-02-02 | |
| 未知 | 郝 郝宣 | 2020-01-17 | |
| 1 KB | Z Zoey Edwards | 2020-01-26 | |
| 5 KB | Z Zoey Edwards | 2020-01-26 | |
| 未知 | Z Zoey Edwards | 2020-01-26 | |
| 2 KB | Z Zoey Edwards | 2020-01-26 |
Code
<script setup lang="ts">
import * as dateFns from 'date-fns';
import { Avatar, Table, type ColumnProps } from '@fibrous/semi-ui-vue';
interface Row {
key: string;
name: string;
nameIconSrc: string;
size: number | undefined;
owner: string;
updateTime: string;
avatarBg: 'grey' | 'red' | 'light-blue';
}
const figmaIconUrl = '/assets/placeholder/app.svg';
const docIconUrl = '/assets/docs-icon.png';
const columns: ColumnProps<Row>[] = [
{
title: '标题',
dataIndex: 'name',
width: 400,
},
{
title: '大小',
dataIndex: 'size',
sorter: (r1, r2, order) => {
const a = r1.size;
const b = r2.size;
if (typeof a === 'number' && typeof b === 'number') {
return a - b; // 数字正常比较大小
} else if (typeof a === 'undefined') {
return order === 'ascend' ? 1 : -1; // undefined 在后面
} else if (typeof b === 'undefined') {
return order === 'ascend' ? -1 : 1; // undefined 在后面
} else {
return 0; // 保持原来的顺序
}
},
showSortTip: true,
},
{
title: '所有者',
dataIndex: 'owner',
},
{
title: '更新日期',
dataIndex: 'updateTime',
},
];
const dataSource: Row[] = [
{
key: '1',
name: 'Semi Design 设计稿.fig',
nameIconSrc: figmaIconUrl,
size: 3,
owner: '姜鹏志',
updateTime: '2020-02-02 05:13',
avatarBg: 'grey',
},
{
key: '2',
name: 'Semi Design 分享演示文稿',
nameIconSrc: docIconUrl,
size: undefined,
owner: '郝宣',
updateTime: '2020-01-17 05:31',
avatarBg: 'red',
},
{
key: '3',
name: '设计文档 3',
nameIconSrc: docIconUrl,
size: 1,
owner: 'Zoey Edwards',
updateTime: '2020-01-26 11:01',
avatarBg: 'light-blue',
},
{
key: '4',
name: '设计文档 4',
nameIconSrc: docIconUrl,
size: 5,
owner: 'Zoey Edwards',
updateTime: '2020-01-26 11:01',
avatarBg: 'light-blue',
},
{
key: '5',
name: '设计文档 5',
nameIconSrc: docIconUrl,
size: undefined,
owner: 'Zoey Edwards',
updateTime: '2020-01-26 11:01',
avatarBg: 'light-blue',
},
{
key: '6',
name: '设计文档 6',
nameIconSrc: docIconUrl,
size: 2,
owner: 'Zoey Edwards',
updateTime: '2020-01-26 11:01',
avatarBg: 'light-blue',
},
];
</script>
<template>
<Table :columns="columns" :dataSource="dataSource">
<template #cell="{ column, record, text }">
<div v-if="column.dataIndex === 'name'">
<Avatar alt="" shape="square" size="small" :src="figmaIconUrl" :style="{ marginRight: '12px' }" />
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'size'">{{ text ? `${text} KB` : '未知' }}</template>
<div v-else-if="column.dataIndex === 'owner'">
<Avatar :color="record.avatarBg" size="small" :style="{ marginRight: '4px' }">
{{ typeof text === 'string' && text.slice(0, 1) }}
</Avatar>
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'updateTime'">
{{ dateFns.format(new Date(text), 'yyyy-MM-dd') }}
</template>
</template>
</Table>
</template>Custom Header Filtering
If you need to display the filter input box in the table header, render the column title with the #headerCell slot (or the #title slot of Table.Column) and use it with filteredValue. The title of a column stays plain text and is shown when the slot outputs nothing.
标题 | 交付状态 | 所有者 | ||
|---|---|---|---|---|
| 0 KB | 已交付 | 姜 姜鹏志 | 2024-01-25 | |
| 5 KB | 待评审 | 郝 郝宣 | 2024-01-30 | |
| 10 KB | 已交付 | 姜 姜鹏志 | 2024-02-04 | |
| 15 KB | 待评审 | 郝 郝宣 | 2024-02-09 | |
| 20 KB | 已交付 | 姜 姜鹏志 | 2024-02-14 | |
| 25 KB | 待评审 | 郝 郝宣 | 2024-02-19 | |
| 30 KB | 已交付 | 姜 姜鹏志 | 2024-02-24 | |
| 35 KB | 待评审 | 郝 郝宣 | 2024-02-29 | |
| 40 KB | 已交付 | 姜 姜鹏志 | 2024-03-05 | |
| 45 KB | 待评审 | 郝 郝宣 | 2024-03-10 |
Code
<script setup lang="ts">
import { computed, ref } from 'vue';
import * as dateFns from 'date-fns';
import { IconClear, IconComment, IconTickCircle } from '@fibrous/semi-icons-vue';
import { Avatar, Input, Space, Table, Tag, type ColumnProps } from '@fibrous/semi-ui-vue';
const DAY = 24 * 60 * 60 * 1000;
const figmaIconUrl = '/assets/placeholder/app.svg';
interface Row {
key: string;
name: string;
owner: string;
size: number;
status: 'success' | 'wait';
updateTime: number;
avatarBg: 'grey' | 'red';
}
const tagConfig = {
success: { color: 'green', icon: IconTickCircle, text: '已交付' },
pending: { color: 'pink', icon: IconClear, text: '已延期' },
wait: { color: 'cyan', icon: IconComment, text: '待评审' },
} as const;
const getData = () => {
const data: Row[] = [];
for (let i = 0; i < 46; i++) {
const isSemiDesign = i % 2 === 0;
const randomNumber = (i * 1000) % 199;
data.push({
key: '' + i,
name: isSemiDesign ? `Semi Design 设计稿${i}.fig` : `Semi D2C 首页${i}.fig`,
owner: isSemiDesign ? '姜鹏志' : '郝宣',
size: randomNumber,
status: isSemiDesign ? 'success' : 'wait',
updateTime: new Date('2024-01-25').valueOf() + randomNumber * DAY,
avatarBg: isSemiDesign ? 'grey' : 'red',
});
}
return data;
};
const dataSource = getData();
const filteredValue = ref<string[]>([]);
// composition makes the Input report the value once an IME composition ends
const handleChange = (value: string) => {
filteredValue.value = value ? [value] : [];
};
const columns = computed((): ColumnProps<Row>[] => [
{
title: '标题',
dataIndex: 'name',
width: 400,
onFilter: (value, record) => record.name.includes(value),
filteredValue: filteredValue.value,
},
{
title: '大小',
dataIndex: 'size',
sorter: (a, b) => (a.size - b.size > 0 ? 1 : -1),
},
{
title: '交付状态',
dataIndex: 'status',
},
{
title: '所有者',
dataIndex: 'owner',
},
{
title: '更新日期',
dataIndex: 'updateTime',
sorter: (a, b) => (a.updateTime - b.updateTime > 0 ? 1 : -1),
},
]);
</script>
<template>
<Table :columns="columns" :dataSource="dataSource">
<template #headerCell="{ column, title }">
<Space v-if="column.dataIndex === 'name'">
<span>{{ title }}</span>
<Input composition placeholder="请输入筛选值" showClear :style="{ width: '200px' }" @change="handleChange" />
</Space>
</template>
<template #cell="{ column, record, text }">
<div v-if="column.dataIndex === 'name'">
<Avatar alt="" shape="square" size="small" :src="figmaIconUrl" :style="{ marginRight: '12px' }" />
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'size'">{{ text }} KB</template>
<Tag v-else-if="column.dataIndex === 'status'" :color="tagConfig[text as Row['status']].color" shape="circle" :style="{ userSelect: 'text' }">
<template #prefixIcon>
<component :is="tagConfig[text as Row['status']].icon" />
</template>
{{ tagConfig[text as Row['status']].text }}
</Tag>
<div v-else-if="column.dataIndex === 'owner'">
<Avatar :color="record.avatarBg" size="small" :style="{ marginRight: '4px' }">
{{ typeof text === 'string' && text.slice(0, 1) }}
</Avatar>
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'updateTime'">
{{ dateFns.format(new Date(text), 'yyyy-MM-dd') }}
</template>
</template>
</Table>
</template>Custom Filter Rendering
Set filterDropdown of the column to true, then customize the filter panel with the #filterDropdown slot. The slot can be written on Table (called for every column whose filterDropdown is true, tell the columns apart with column) or on Table.Column; when the slot outputs nothing, the filter menu is shown.
You can call onTempFilteredValueChange to store the filter value when the user enters the filter value, and call onConfirm to trigger the actual filtering after the filter value is entered. You can also filter directly through onConfirm({ filteredValue }).
The reason for providing tempFilteredValue is that in scenarios where temporary filtered values need to be stored, there is no need to declare a ref to save this temporary filtered value.
interface TableFilterDropdownSlotProps {
/** The configuration of the current column */
column: ColumnProps;
/** Filter configuration items, `undefined` when the column has no `filters` */
filters: TableFilter[] | undefined;
/** Temporary filter value, the applied filter value when nothing is stored */
tempFilteredValue: any[] | undefined;
/** Set temporary filter value */
onTempFilteredValueChange: (value: any[] | undefined) => void;
/** `onConfirm` will assign `tempFilteredValue` to `filteredValue` by default and emit the `change` event. You can also set the filter value directly by passing in `filteredValue` */
onConfirm: (options?: { closeDropdown?: boolean; filteredValue?: any[] }) => void;
/** Clear filter values and temporary filter values */
onClear: (options?: { closeDropdown?: boolean }) => void;
/** Close dropdown */
onClose: () => void;
/** Restore the temporary filter value to the applied filter value */
onReset: () => void;
}
The onVisibleChange in filterDropdownProps does not take effect; get the visibility of the filter panel through onFilterDropdownVisibleChange of the column.
标题 | 所有者 | ||
|---|---|---|---|
| 0 KB | 姜 姜鹏志 | 2024-05-06 | |
| 10 KB | 姜 姜鹏志 | 2024-05-16 | |
| 20 KB | 姜 姜鹏志 | 2024-05-26 | |
| 30 KB | 姜 姜鹏志 | 2024-06-05 | |
| 40 KB | 姜 姜鹏志 | 2024-06-15 | |
| 50 KB | 姜 姜鹏志 | 2024-06-25 | |
| 60 KB | 姜 姜鹏志 | 2024-07-05 | |
| 70 KB | 姜 姜鹏志 | 2024-07-15 | |
| 80 KB | 姜 姜鹏志 | 2024-07-25 | |
| 90 KB | 姜 姜鹏志 | 2024-08-04 |
Code
<script setup lang="ts">
import { nextTick, useTemplateRef } from 'vue';
import * as dateFns from 'date-fns';
import { Avatar, Button, Input, Space, Table, type ColumnProps, type InputHandle } from '@fibrous/semi-ui-vue';
const DAY = 24 * 60 * 60 * 1000;
const figmaIconUrl = '/assets/placeholder/app.svg';
interface Row {
key: string;
name: string;
owner: string;
size: number;
updateTime: number;
avatarBg: 'grey' | 'red';
}
const getData = () => {
const data: Row[] = [];
for (let i = 0; i < 46; i++) {
const isSemiDesign = i % 2 === 0;
const randomNumber = (i * 1000) % 199;
data.push({
key: '' + i,
name: isSemiDesign ? `Semi Design 设计稿${i}.fig` : `Semi D2C 设计稿${i}.fig`,
owner: isSemiDesign ? '姜鹏志' : '郝宣',
size: randomNumber,
updateTime: new Date(2024, 4, 6, 12).valueOf() + randomNumber * DAY,
avatarBg: isSemiDesign ? 'grey' : 'red',
});
}
return data;
};
const dataSource = getData();
const nameInput = useTemplateRef<InputHandle>('nameInput');
const columns: ColumnProps<Row>[] = [
{
title: '标题',
dataIndex: 'name',
width: 400,
onFilter: (value, record) => record.name.includes(value),
filterDropdown: true,
onFilterDropdownVisibleChange: () => {
// the panel is rendered after the visibility changes
void nextTick(() => nameInput.value?.focus());
},
},
{
title: '大小',
dataIndex: 'size',
sorter: (a, b) => (a.size - b.size > 0 ? 1 : -1),
},
{
title: '所有者',
dataIndex: 'owner',
onFilter: (value, record) => record.owner.includes(value),
defaultFilteredValue: ['姜鹏志'],
filterDropdown: true,
},
{
title: '更新日期',
dataIndex: 'updateTime',
sorter: (a, b) => (a.updateTime - b.updateTime > 0 ? 1 : -1),
},
];
</script>
<template>
<Table :columns="columns" :dataSource="dataSource">
<template #filterDropdown="{ column, tempFilteredValue, onTempFilteredValueChange, onConfirm, onClear, onClose }">
<Space v-if="column.dataIndex === 'name'" align="start" :style="{ padding: '8px' }" vertical>
<Input ref="nameInput" :modelValue="tempFilteredValue?.[0]" @update:modelValue="onTempFilteredValueChange($event ? [$event] : [])" />
<Space>
<Button @click="onConfirm({ closeDropdown: true })">筛选 + 关闭</Button>
<Button @click="onClear({ closeDropdown: true })">清除 + 关闭</Button>
<Button @click="onClose()">直接关闭</Button>
</Space>
</Space>
<Space v-else align="start" :style="{ padding: '8px' }" vertical>
<Input :modelValue="tempFilteredValue?.[0]" @update:modelValue="onTempFilteredValueChange($event ? [$event] : [])" />
<Space>
<Button @click="onConfirm({ closeDropdown: false })">筛选后不关闭</Button>
<Button @click="onClear({ closeDropdown: false })">清除后不关闭</Button>
<Button @click="onClose()">直接关闭</Button>
</Space>
</Space>
</template>
<template #cell="{ column, record, text }">
<div v-if="column.dataIndex === 'name'">
<Avatar alt="" shape="square" size="small" :src="figmaIconUrl" :style="{ marginRight: '12px' }" />
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'size'">{{ text }} KB</template>
<div v-else-if="column.dataIndex === 'owner'">
<Avatar :color="record.avatarBg" size="small" :style="{ marginRight: '4px' }">
{{ typeof text === 'string' && text.slice(0, 1) }}
</Avatar>
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'updateTime'">
{{ dateFns.format(new Date(text), 'yyyy-MM-dd') }}
</template>
</template>
</Table>
</template>Filter Confirm Mode
By setting filterConfirmMode='confirm', the filter dropdown panel can support confirm mode. In this mode:
- Clicking filter items will not take effect immediately, but will be temporarily stored
- The bottom of the dropdown panel will show "Confirm" and "Reset" buttons
- Clicking the "Confirm" button will apply the filter conditions and close the dropdown panel
- Clicking the "Reset" button will restore to the initial state when the dropdown was opened (will not close the panel)
This feature is suitable for scenarios where multiple filter conditions need to be selected before applying them at once, avoiding triggering filtering on every click.
标题 | 所有者 | ||
|---|---|---|---|
| 0 KB | 姜 姜鹏志 | 2024-01-25 | |
| 5 KB | 郝 郝宣 | 2024-01-30 | |
| 10 KB | 姜 姜鹏志 | 2024-02-04 | |
| 15 KB | 郝 郝宣 | 2024-02-09 | |
| 20 KB | 姜 姜鹏志 | 2024-02-14 | |
| 25 KB | 郝 郝宣 | 2024-02-19 | |
| 30 KB | 姜 姜鹏志 | 2024-02-24 | |
| 35 KB | 郝 郝宣 | 2024-02-29 | |
| 40 KB | 姜 姜鹏志 | 2024-03-05 | |
| 45 KB | 郝 郝宣 | 2024-03-10 |
Code
<script setup lang="ts">
import * as dateFns from 'date-fns';
import { Avatar, Table, type ColumnProps } from '@fibrous/semi-ui-vue';
const DAY = 24 * 60 * 60 * 1000;
const figmaIconUrl = '/assets/placeholder/app.svg';
interface Row {
key: string;
name: string;
owner: string;
size: number;
updateTime: number;
avatarBg: 'grey' | 'red';
}
const columns: ColumnProps<Row>[] = [
{
title: '标题',
dataIndex: 'name',
width: 300,
filters: [
{
text: 'Semi Design 设计稿',
value: 'Semi Design',
},
{
text: 'Semi Pro 设计稿',
value: 'Semi Pro',
},
],
onFilter: (value, record) => record.name.includes(value),
filterMultiple: true,
filterConfirmMode: 'confirm',
},
{
title: '大小',
dataIndex: 'size',
sorter: (a, b) => (a.size - b.size > 0 ? 1 : -1),
},
{
title: '所有者',
dataIndex: 'owner',
filters: [
{
text: '姜鹏志',
value: '姜鹏志',
},
{
text: '郝宣',
value: '郝宣',
},
],
onFilter: (value, record) => record.owner.includes(value),
filterMultiple: true,
filterConfirmMode: 'confirm',
},
{
title: '更新日期',
dataIndex: 'updateTime',
sorter: (a, b) => (a.updateTime - b.updateTime > 0 ? 1 : -1),
},
];
const getData = () => {
const data: Row[] = [];
for (let i = 0; i < 20; i++) {
const isSemiDesign = i % 2 === 0;
const randomNumber = (i * 1000) % 199;
data.push({
key: '' + i,
name: isSemiDesign ? `Semi Design 设计稿${i}.fig` : `Semi Pro 首页${i}.fig`,
owner: isSemiDesign ? '姜鹏志' : '郝宣',
size: randomNumber,
updateTime: new Date('2024-01-25').valueOf() + randomNumber * DAY,
avatarBg: isSemiDesign ? 'grey' : 'red',
});
}
return data;
};
const dataSource = getData();
</script>
<template>
<Table :columns="columns" :dataSource="dataSource">
<template #cell="{ column, text, record }">
<div v-if="column.dataIndex === 'name'">
<Avatar alt="" shape="square" size="small" :src="figmaIconUrl" :style="{ marginRight: '12px' }" />
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'size'">{{ text }} KB</template>
<div v-else-if="column.dataIndex === 'owner'">
<Avatar :color="record.avatarBg" size="small" :style="{ marginRight: '4px' }">
{{ text.slice(0, 1) }}
</Avatar>
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'updateTime'">
{{ dateFns.format(new Date(text), 'yyyy-MM-dd') }}
</template>
</template>
</Table>
</template>Custom Filter Item Rendering
Use the #filterDropdownItem slot to customize the rendering of each filter item. The slot can be written on Table or on Table.Column (which takes precedence); when the slot outputs nothing, the default filter item is shown. The parameters are:
column: ColumnPropsthe configuration of the current column;text: string | undefinedthe text of the current filter item;value: anythe value of the current filter item;checked: booleanwhether the current filter item has been selected;filteredValue: any[]the filter values the menu currently shows; in confirm mode these are the temporary values that have not been applied;level: numberthe level of the menu the current filter item is in,0for the top level menu;filterMultiple: booleanwhether the current filter item is multi-select;onChange: (event: MouseEvent) => voidtoggles the selection of the current filter item, bind it to theclickof the item.
| 所有者 |
|---|
| 0 KB | 姜 姜鹏志 | 2024-05-06 | ||
| 5 KB | 郝 郝宣 | 2024-05-11 | ||
| 10 KB | 姜 姜鹏志 | 2024-05-16 | ||
| 15 KB | 郝 郝宣 | 2024-05-21 | ||
| 20 KB | 姜 姜鹏志 | 2024-05-26 | ||
| 25 KB | 郝 郝宣 | 2024-05-31 | ||
| 30 KB | 姜 姜鹏志 | 2024-06-05 | ||
| 35 KB | 郝 郝宣 | 2024-06-10 | ||
| 40 KB | 姜 姜鹏志 | 2024-06-15 | ||
| 45 KB | 郝 郝宣 | 2024-06-20 |
Code
<script setup lang="ts">
import * as dateFns from 'date-fns';
import { Avatar, DropdownItem, Table, type ColumnProps, type RowSelectionProps } from '@fibrous/semi-ui-vue';
const DAY = 24 * 60 * 60 * 1000;
const figmaIconUrl = '/assets/placeholder/app.svg';
interface Row {
key: string;
name: string;
owner: string;
size: number;
updateTime: number;
avatarBg: 'grey' | 'red';
}
const columns: ColumnProps<Row>[] = [
{
title: '标题',
dataIndex: 'name',
width: 400,
filters: [
{
text: 'Semi Design 设计稿',
value: 'Semi Design 设计稿',
},
{
text: 'Semi D2C 设计稿',
value: 'Semi D2C 设计稿',
},
],
onFilter: (value, record) => record.name.includes(value),
filterDropdownProps: {
showTick: true,
},
sorter: (a, b) => (a.name.length - b.name.length > 0 ? 1 : -1),
},
{
title: '大小',
dataIndex: 'size',
sorter: (a, b) => (a.size - b.size > 0 ? 1 : -1),
},
{
title: '所有者',
dataIndex: 'owner',
},
{
title: '更新日期',
dataIndex: 'updateTime',
sorter: (a, b) => (a.updateTime - b.updateTime > 0 ? 1 : -1),
},
];
const getData = () => {
const data: Row[] = [];
for (let i = 0; i < 46; i++) {
const isSemiDesign = i % 2 === 0;
const randomNumber = (i * 1000) % 199;
data.push({
key: '' + i,
name: isSemiDesign ? `Semi Design 设计稿${i}.fig` : `Semi D2C 设计稿${i}.fig`,
owner: isSemiDesign ? '姜鹏志' : '郝宣',
size: randomNumber,
updateTime: new Date(2024, 4, 6, 12).valueOf() + randomNumber * DAY,
avatarBg: isSemiDesign ? 'grey' : 'red',
});
}
return data;
};
const dataSource = getData();
const rowSelection: RowSelectionProps<Row> = {
onChange: (selectedRowKeys, selectedRows) => {
console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
},
getCheckboxProps: (record) => ({
disabled: record.name === 'Semi Design 设计稿0.fig', // 这一行不可勾选
name: record.name,
}),
};
const scroll = { y: 300 };
</script>
<template>
<Table :columns="columns" :dataSource="dataSource" :rowSelection="rowSelection" :scroll="scroll">
<template #cell="{ column, text, record }">
<div v-if="column.dataIndex === 'name'">
<Avatar alt="" shape="square" size="small" :src="figmaIconUrl" :style="{ marginRight: '12px' }" />
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'size'">{{ text }} KB</template>
<div v-else-if="column.dataIndex === 'owner'">
<Avatar :color="record.avatarBg" size="small" :style="{ marginRight: '4px' }">
{{ text.slice(0, 1) }}
</Avatar>
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'updateTime'">
{{ dateFns.format(new Date(text), 'yyyy-MM-dd') }}
</template>
</template>
<template #filterDropdownItem="{ text, checked, onChange }">
<DropdownItem :active="checked" @click="onChange">{{ text }}</DropdownItem>
</template>
</Table>
</template>A Table That Can Be Expanded
A Common Table That Can Be Expanded
If you need to render a table that can be expanded, in addition to the #expandedRow slot of Table (parameters record, index and expanded; a row whose output is empty renders no expanded content), you must specify rowKey(by default key), Table will be based on rowKey Gets a row unique identifier. The expanded rows can be controlled with v-model:expandedRowKeys.
- If
rowKeyis a Function, the result ofrowKey(record)is taken as the row unique ID - If
rowKeyis a string type, you takerecord[rowKey]as the row unique ID
| 标题 | 大小 | 所有者 | 更新日期 | ||
|---|---|---|---|---|---|
| 2M | 姜 姜鹏志 | 2020-02-02 05:13 | |||
| 2M | 郝 郝宣 | 2020-01-17 05:31 | |||
| 34KB | Z Zoey Edwards | 2020-01-26 11:01 |
Code
<script setup lang="ts">
import { IconMore } from '@fibrous/semi-icons-vue';
import { Avatar, Descriptions, Table, Tag, type ColumnProps, type RowSelectionProps } from '@fibrous/semi-ui-vue';
interface Row {
key: string;
name: string;
nameIconSrc: string;
size: string;
owner: string;
updateTime: string;
avatarBg: 'grey' | 'red' | 'light-blue';
}
const columns: ColumnProps<Row>[] = [
{ title: '标题', width: 500, dataIndex: 'name' },
{ title: '大小', dataIndex: 'size' },
{ title: '所有者', dataIndex: 'owner' },
{ title: '更新日期', dataIndex: 'updateTime' },
{ title: '', dataIndex: 'operate' },
];
const data: Row[] = [
{
key: '1',
name: 'Semi Design 设计稿.fig',
nameIconSrc: '/assets/placeholder/app.svg',
size: '2M',
owner: '姜鹏志',
updateTime: '2020-02-02 05:13',
avatarBg: 'grey',
},
{
key: '2',
name: 'Semi Design 分享演示文稿',
nameIconSrc: '/assets/docs-icon.png',
size: '2M',
owner: '郝宣',
updateTime: '2020-01-17 05:31',
avatarBg: 'red',
},
{
key: '3',
name: '设计文档',
nameIconSrc: '/assets/docs-icon.png',
size: '34KB',
owner: 'Zoey Edwards',
updateTime: '2020-01-26 11:01',
avatarBg: 'light-blue',
},
];
const expandData: Record<number, { key: string; value: string }[]> = {
0: [
{ key: '实际用户数量', value: '1,480,000' },
{ key: '7 天留存', value: '98%' },
{ key: '安全等级', value: '3 级' },
{ key: '垂类标签', value: '设计' },
{ key: '认证状态', value: '未认证' },
],
1: [
{ key: '实际用户数量', value: '2,480,000' },
{ key: '7 天留存', value: '90%' },
{ key: '安全等级', value: '1 级' },
{ key: '垂类标签', value: '模板' },
{ key: '认证状态', value: '已认证' },
],
2: [
{ key: '实际用户数量', value: '2,920,000' },
{ key: '7 天留存', value: '98%' },
{ key: '安全等级', value: '2 级' },
{ key: '垂类标签', value: '文档' },
{ key: '认证状态', value: '已认证' },
],
};
const rowSelection: RowSelectionProps<Row> = {
getCheckboxProps: (record) => ({
disabled: record.name === '设计文档', // 这一行不可勾选
name: record.name,
}),
onSelect: (record, selected) => {
console.log(`select row: ${selected}`, record);
},
onSelectAll: (selected, selectedRows) => {
console.log(`select all rows: ${selected}`, selectedRows);
},
onChange: (selectedRowKeys, selectedRows) => {
console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
},
};
</script>
<template>
<Table :columns="columns" :dataSource="data" :pagination="false" :rowSelection="rowSelection" rowKey="name">
<template #cell="{ column, text, record }">
<span v-if="column.dataIndex === 'name'">
<Avatar alt="" shape="square" size="small" :src="record.nameIconSrc" :style="{ marginRight: '12px' }" />
{{ text }}
</span>
<div v-else-if="column.dataIndex === 'owner'">
<Avatar :color="record.avatarBg" size="small" :style="{ marginRight: '4px' }">
{{ text.slice(0, 1) }}
</Avatar>
{{ text }}
</div>
<IconMore v-else-if="column.dataIndex === 'operate'" />
</template>
<template #expandedRow="{ index }">
<Descriptions align="justify" :data="expandData[index]">
<template #value="{ item }">
<Tag v-if="item.key === '垂类标签'" :style="{ margin: 0 }">{{ item.value }}</Tag>
<template v-else>{{ item.value }}</template>
</template>
</Descriptions>
</template>
</Table>
</template>The Unfold Button Is Rendered In a Separated Column
By default, the expansion button will be rendered in the same cell as the first copy, and you can set hideExpandedColumn to false to render as a separate column:
| 标题 | 大小 | 所有者 | 更新日期 | |||
|---|---|---|---|---|---|---|
| 2M | 姜 姜鹏志 | 2020-02-02 05:13 | ||||
| 2M | 郝 郝宣 | 2020-01-17 05:31 | ||||
| 34KB | Z Zoey Edwards | 2020-01-26 11:01 |
Code
<script setup lang="ts">
import { IconMore } from '@fibrous/semi-icons-vue';
import { Avatar, Descriptions, Table, Tag, type ColumnProps, type RowSelectionProps } from '@fibrous/semi-ui-vue';
interface Row {
key: string;
name: string;
nameIconSrc: string;
size: string;
owner: string;
updateTime: string;
avatarBg: 'grey' | 'red' | 'light-blue';
}
const columns: ColumnProps<Row>[] = [
{ title: '标题', width: 500, dataIndex: 'name' },
{ title: '大小', dataIndex: 'size' },
{ title: '所有者', dataIndex: 'owner' },
{ title: '更新日期', dataIndex: 'updateTime' },
{ title: '', dataIndex: 'operate' },
];
const data: Row[] = [
{
key: '1',
name: 'Semi Design 设计稿.fig',
nameIconSrc: '/assets/placeholder/app.svg',
size: '2M',
owner: '姜鹏志',
updateTime: '2020-02-02 05:13',
avatarBg: 'grey',
},
{
key: '2',
name: 'Semi Design 分享演示文稿',
nameIconSrc: '/assets/docs-icon.png',
size: '2M',
owner: '郝宣',
updateTime: '2020-01-17 05:31',
avatarBg: 'red',
},
{
key: '3',
name: '设计文档',
nameIconSrc: '/assets/docs-icon.png',
size: '34KB',
owner: 'Zoey Edwards',
updateTime: '2020-01-26 11:01',
avatarBg: 'light-blue',
},
];
const expandData: Record<number, { key: string; value: string }[]> = {
0: [
{ key: '实际用户数量', value: '1,480,000' },
{ key: '7 天留存', value: '98%' },
{ key: '安全等级', value: '3 级' },
{ key: '垂类标签', value: '设计' },
{ key: '认证状态', value: '未认证' },
],
1: [
{ key: '实际用户数量', value: '2,480,000' },
{ key: '7 天留存', value: '90%' },
{ key: '安全等级', value: '1 级' },
{ key: '垂类标签', value: '模板' },
{ key: '认证状态', value: '已认证' },
],
2: [
{ key: '实际用户数量', value: '2,920,000' },
{ key: '7 天留存', value: '98%' },
{ key: '安全等级', value: '2 级' },
{ key: '垂类标签', value: '文档' },
{ key: '认证状态', value: '已认证' },
],
};
const rowSelection: RowSelectionProps<Row> = {
getCheckboxProps: (record) => ({
disabled: record.name === '设计文档', // 这一行不可勾选
name: record.name,
}),
onSelect: (record, selected) => {
console.log(`select row: ${selected}`, record);
},
onSelectAll: (selected, selectedRows) => {
console.log(`select all rows: ${selected}`, selectedRows);
},
onChange: (selectedRowKeys, selectedRows) => {
console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
},
};
</script>
<template>
<Table :columns="columns" :dataSource="data" :hideExpandedColumn="false" :pagination="false" :rowSelection="rowSelection" rowKey="name">
<template #cell="{ column, text, record }">
<span v-if="column.dataIndex === 'name'">
<Avatar alt="" shape="square" size="small" :src="record.nameIconSrc" :style="{ marginRight: '12px' }" />
{{ text }}
</span>
<div v-else-if="column.dataIndex === 'owner'">
<Avatar :color="record.avatarBg" size="small" :style="{ marginRight: '4px' }">
{{ text.slice(0, 1) }}
</Avatar>
{{ text }}
</div>
<IconMore v-else-if="column.dataIndex === 'operate'" />
</template>
<template #expandedRow="{ index }">
<Descriptions align="justify" :data="expandData[index]">
<template #value="{ item }">
<Tag v-if="item.key === '垂类标签'" :style="{ margin: 0 }">{{ item.value }}</Tag>
<template v-else>{{ item.value }}</template>
</template>
</Descriptions>
</template>
</Table>
</template>Turn Off Rendering of Expandable Button of a Row
You can pass the row Expandable method, enter the reference as record, and determine whether the return value is false to close the rendering of the expandable button on a row.
| 标题 | 大小 | 所有者 | 更新日期 | |||
|---|---|---|---|---|---|---|
| 2M | 姜 姜鹏志 | 2020-02-02 05:13 | ||||
| 2M | 郝 郝宣 | 2020-01-17 05:31 | ||||
| 34KB | Z Zoey Edwards | 2020-01-26 11:01 |
Code
<script setup lang="ts">
import { IconMore } from '@fibrous/semi-icons-vue';
import { Avatar, Descriptions, Table, Tag, type ColumnProps, type RowSelectionProps } from '@fibrous/semi-ui-vue';
interface Row {
key: string;
name: string;
nameIconSrc: string;
size: string;
owner: string;
updateTime: string;
avatarBg: 'grey' | 'red' | 'light-blue';
}
const columns: ColumnProps<Row>[] = [
{ title: '标题', width: 500, dataIndex: 'name' },
{ title: '大小', dataIndex: 'size' },
{ title: '所有者', dataIndex: 'owner' },
{ title: '更新日期', dataIndex: 'updateTime' },
{ title: '', dataIndex: 'operate' },
];
const data: Row[] = [
{
key: '1',
name: 'Semi Design 设计稿.fig',
nameIconSrc: '/assets/placeholder/app.svg',
size: '2M',
owner: '姜鹏志',
updateTime: '2020-02-02 05:13',
avatarBg: 'grey',
},
{
key: '2',
name: 'Semi Design 分享演示文稿',
nameIconSrc: '/assets/docs-icon.png',
size: '2M',
owner: '郝宣',
updateTime: '2020-01-17 05:31',
avatarBg: 'red',
},
{
key: '3',
name: '设计文档',
nameIconSrc: '/assets/docs-icon.png',
size: '34KB',
owner: 'Zoey Edwards',
updateTime: '2020-01-26 11:01',
avatarBg: 'light-blue',
},
];
const expandData: Record<number, { key: string; value: string }[]> = {
0: [
{ key: '实际用户数量', value: '1,480,000' },
{ key: '7 天留存', value: '98%' },
{ key: '安全等级', value: '3 级' },
{ key: '垂类标签', value: '设计' },
{ key: '认证状态', value: '未认证' },
],
1: [
{ key: '实际用户数量', value: '2,480,000' },
{ key: '7 天留存', value: '90%' },
{ key: '安全等级', value: '1 级' },
{ key: '垂类标签', value: '模板' },
{ key: '认证状态', value: '已认证' },
],
2: [
{ key: '实际用户数量', value: '2,920,000' },
{ key: '7 天留存', value: '98%' },
{ key: '安全等级', value: '2 级' },
{ key: '垂类标签', value: '文档' },
{ key: '认证状态', value: '已认证' },
],
};
const rowSelection: RowSelectionProps<Row> = {
getCheckboxProps: (record) => ({
disabled: record.name === '设计文档', // 这一行不可勾选
name: record.name,
}),
onSelect: (record, selected) => {
console.log(`select row: ${selected}`, record);
},
onSelectAll: (selected, selectedRows) => {
console.log(`select all rows: ${selected}`, selectedRows);
},
onChange: (selectedRowKeys, selectedRows) => {
console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
},
};
const rowExpandable = (record: Row) => record.name !== '设计文档';
</script>
<template>
<Table :columns="columns" :dataSource="data" :hideExpandedColumn="false" :pagination="false" :rowExpandable="rowExpandable" :rowSelection="rowSelection" rowKey="name">
<template #cell="{ column, text, record }">
<span v-if="column.dataIndex === 'name'">
<Avatar alt="" shape="square" size="small" :src="record.nameIconSrc" :style="{ marginRight: '12px' }" />
{{ text }}
</span>
<div v-else-if="column.dataIndex === 'owner'">
<Avatar :color="record.avatarBg" size="small" :style="{ marginRight: '4px' }">
{{ text.slice(0, 1) }}
</Avatar>
{{ text }}
</div>
<IconMore v-else-if="column.dataIndex === 'operate'" />
</template>
<template #expandedRow="{ index }">
<Descriptions align="justify" :data="expandData[index]">
<template #value="{ item }">
<Tag v-if="item.key === '垂类标签'" :style="{ margin: 0 }">{{ item.value }}</Tag>
<template v-else>{{ item.value }}</template>
</template>
</Descriptions>
</template>
</Table>
</template>Tree Data Display
The table supports the display of tree data and is automatically displayed as a tree table when there are children fields in the data. If you do not need or use other fields, you can configure it with the childrenRecordName. In addition, you can control the indent width of each layer by setting indent Size.
Note: Be sure to provide a "key" for each row of data that is different from the other row values, or use the
rowKeyparameter to specify a property name as the primary key.
Simple example of tree data
| Key | 名称 | 数据类型 | 描述 | 默认值 |
|---|---|---|---|---|
| videos_info | 视频信息 | Object 对象 | 视频的元信息 | 无 |
| text_info | 文本信息 | Object 对象 | 视频的元信息 | 无 |
Code
<script setup lang="ts">
import { Table, type ColumnProps } from '@fibrous/semi-ui-vue';
interface TreeRow {
key?: number;
dataKey: string;
name: string;
type: string;
description: string;
default: string;
children?: TreeRow[];
}
const columns: ColumnProps<TreeRow>[] = [
{
title: 'Key',
dataIndex: 'dataKey',
key: 'dataKey',
},
{
title: '名称',
dataIndex: 'name',
key: 'name',
width: 200,
},
{
title: '数据类型',
dataIndex: 'type',
key: 'type',
width: 400,
},
{
title: '描述',
dataIndex: 'description',
key: 'description',
},
{
title: '默认值',
dataIndex: 'default',
key: 'default',
width: 100,
},
];
const data: TreeRow[] = [
{
key: 1,
dataKey: 'videos_info',
name: '视频信息',
type: 'Object 对象',
description: '视频的元信息',
default: '无',
children: [
{
key: 11,
dataKey: 'status',
name: '视频状态',
type: 'Enum <Integer> 枚举',
description: '视频的可见、推荐状态',
default: '1',
},
{
key: 12,
dataKey: 'vid',
name: '视频 ID',
type: 'String 字符串',
description: '标识视频的唯一 ID',
default: '无',
children: [
{
dataKey: 'video_url',
name: '视频地址',
type: 'String 字符串',
description: '视频的唯一链接',
default: '无',
},
],
},
],
},
{
key: 2,
dataKey: 'text_info',
name: '文本信息',
type: 'Object 对象',
description: '视频的元信息',
default: '无',
children: [
{
key: 21,
dataKey: 'title',
name: '视频标题',
type: 'String 字符串',
description: '视频的标题',
default: '无',
},
{
key: 22,
dataKey: 'video_description',
name: '视频描述',
type: 'String 字符串',
description: '视频的描述',
default: '无',
},
],
},
];
</script>
<template>
<Table :columns="columns" :dataSource="data" defaultExpandAllRows />
</template>Rows of Interchangeable Tree Data
You can do row switching by changing the order of the dataSource elements.
| Key | 名称 | 数据类型 | 描述 | 默认值 | |
|---|---|---|---|---|---|
| videos_info | 视频信息 | Object 对象 | 视频的元信息 | 无 | |
| status | 视频状态 | Enum <Integer> 枚举 | 视频的可见、推荐状态 | 1 | |
| vid | 视频 ID | String 字符串 | 标识视频的唯一 ID | 无 | |
| text_info | 文本信息 | Object 对象 | 视频的元信息 | 无 | |
| title | 视频标题 | String 字符串 | 视频的标题 | 无 | |
| video_description | 视频描述 | String 字符串 | 视频的描述 | 无 |
Code
<script setup lang="ts">
import { ref, shallowRef } from 'vue';
import { IconArrowDown, IconArrowUp } from '@fibrous/semi-icons-vue';
import { Button, Table, type ColumnProps } from '@fibrous/semi-ui-vue';
interface TreeRow {
key?: number;
dataKey: string;
name: string;
type: string;
description: string;
default: string;
children?: TreeRow[];
}
const raw: TreeRow[] = [
{
key: 1,
dataKey: 'videos_info',
name: '视频信息',
type: 'Object 对象',
description: '视频的元信息',
default: '无',
children: [
{
key: 11,
dataKey: 'status',
name: '视频状态',
type: 'Enum <Integer> 枚举',
description: '视频的可见、推荐状态',
default: '1',
},
{
key: 12,
dataKey: 'vid',
name: '视频 ID',
type: 'String 字符串',
description: '标识视频的唯一 ID',
default: '无',
children: [
{
dataKey: 'video_url',
name: '视频地址',
type: 'String 字符串',
description: '视频的唯一链接',
default: '无',
},
],
},
],
},
{
key: 2,
dataKey: 'text_info',
name: '文本信息',
type: 'Object 对象',
description: '视频的元信息',
default: '无',
children: [
{
key: 21,
dataKey: 'title',
name: '视频标题',
type: 'String 字符串',
description: '视频的标题',
default: '无',
},
{
key: 22,
dataKey: 'video_description',
name: '视频描述',
type: 'String 字符串',
description: '视频的描述',
default: '无',
},
],
},
];
const rowKey = 'key';
const childrenRecordName = 'children';
const columns: ColumnProps<TreeRow>[] = [
{
title: 'Key',
dataIndex: 'dataKey',
key: 'dataKey',
},
{
title: '名称',
dataIndex: 'name',
key: 'name',
width: 200,
},
{
title: '数据类型',
dataIndex: 'type',
key: 'type',
},
{
title: '描述',
dataIndex: 'description',
key: 'description',
},
{
title: '默认值',
dataIndex: 'default',
key: 'default',
width: 100,
},
{
key: 'operation',
},
];
const expandedRowKeys = ref<(string | number)[]>([1, 2]);
const data = shallowRef(raw);
const getSameLevelRecords = (key: number | undefined, rows: TreeRow[]): TreeRow[] => {
if (key == null) {
return [];
}
if (rows.some((item) => item[rowKey] === key)) {
return rows;
}
for (const item of rows) {
const records = getSameLevelRecords(key, item[childrenRecordName] ?? []);
if (records.length) {
return records;
}
}
return [];
};
// Returns a copy of the tree in which the record swaps places with its sibling `offset` rows away.
const moveRecord = (rows: TreeRow[], key: number | undefined, offset: -1 | 1): TreeRow[] => {
const index = rows.findIndex((item) => item[rowKey] === key);
if (index === -1) {
return rows.map((item) => (item[childrenRecordName] ? { ...item, children: moveRecord(item[childrenRecordName], key, offset) } : item));
}
const next = [...rows];
[next[index], next[index + offset]] = [next[index + offset], next[index]];
return next;
};
const canMove = (record: TreeRow, offset: -1 | 1) => {
const records = getSameLevelRecords(record[rowKey], data.value);
const index = records.findIndex((item) => item[rowKey] === record[rowKey]);
return index >= 0 && index + offset >= 0 && index + offset < records.length;
};
const move = (record: TreeRow, offset: -1 | 1) => {
data.value = moveRecord(data.value, record[rowKey], offset);
};
</script>
<template>
<Table v-model:expandedRowKeys="expandedRowKeys" :childrenRecordName="childrenRecordName" :columns="columns" :dataSource="data" :rowKey="rowKey">
<template #cell="{ column, record }">
<template v-if="column.key === 'operation'">
<Button aria-label="上移" :disabled="!canMove(record, -1)" @click="move(record, -1)">
<template #icon>
<IconArrowUp />
</template>
</Button>
<Button aria-label="下移" :disabled="!canMove(record, 1)" @click="move(record, 1)">
<template #icon>
<IconArrowDown />
</template>
</Button>
</template>
</template>
</Table>
</template>Tree Selection
By default, the row selection of the table is independent. You can simulate a tree selection by defining selectedRowKeys.
| Key | 名称 | 数据类型 | 描述 | 默认值 | |
|---|---|---|---|---|---|
| videos_info | 视频信息 | Object 对象 | 视频的元信息 | 无 | |
| text_info | 文本信息 | Object 对象 | 视频的元信息 | 无 |
Code
<script setup lang="ts">
import { computed, ref } from 'vue';
import { pull, union } from 'es-toolkit';
import { Table, type ColumnProps, type RowSelectionProps } from '@fibrous/semi-ui-vue';
interface TreeRow {
key: number;
dataKey: string;
name: string;
type: string;
description: string;
default: string;
children?: TreeRow[];
}
type RowKey = string | number;
const childrenRecordName = 'children';
const rowKey = 'key';
const columns: ColumnProps<TreeRow>[] = [
{
title: 'Key',
dataIndex: 'dataKey',
key: 'dataKey',
},
{
title: '名称',
dataIndex: 'name',
key: 'name',
width: 200,
},
{
title: '数据类型',
dataIndex: 'type',
key: 'type',
width: 400,
},
{
title: '描述',
dataIndex: 'description',
key: 'description',
},
{
title: '默认值',
dataIndex: 'default',
key: 'default',
width: 100,
},
];
const data: TreeRow[] = [
{
key: 1,
dataKey: 'videos_info',
name: '视频信息',
type: 'Object 对象',
description: '视频的元信息',
default: '无',
children: [
{
key: 11,
dataKey: 'status',
name: '视频状态',
type: 'Enum <Integer> 枚举',
description: '视频的可见、推荐状态',
default: '1',
},
{
key: 12,
dataKey: 'vid',
name: '视频 ID',
type: 'String 字符串',
description: '标识视频的唯一 ID',
default: '无',
children: [
{
key: 121,
dataKey: 'video_url',
name: '视频地址',
type: 'String 字符串',
description: '视频的唯一链接',
default: '无',
},
],
},
],
},
{
key: 2,
dataKey: 'text_info',
name: '文本信息',
type: 'Object 对象',
description: '视频的元信息',
default: '无',
children: [
{
key: 21,
dataKey: 'title',
name: '视频标题',
type: 'String 字符串',
description: '视频的标题',
default: '无',
},
{
key: 22,
dataKey: 'video_description',
name: '视频描述',
type: 'String 字符串',
description: '视频的描述',
default: '无',
},
],
},
];
// Collects the keys of the rows and all their descendants.
const collectKeys = (rows: TreeRow[]): RowKey[] => rows.flatMap((row) => [row.key, ...collectKeys(row.children ?? [])]);
const selectedRowKeys = ref<RowKey[]>([]);
// Selecting a row selects its descendants too, and clearing it clears them.
const doSelect = (record: TreeRow, selected: boolean) => {
const keys = [record.key, ...collectKeys(record.children ?? [])];
selectedRowKeys.value = selected ? union(selectedRowKeys.value, keys) : pull([...selectedRowKeys.value], keys);
};
const doSelectAll = (selected: boolean) => {
selectedRowKeys.value = selected ? collectKeys(data) : [];
};
const rowSelection = computed<RowSelectionProps<TreeRow>>(() => ({
selectedRowKeys: selectedRowKeys.value,
onSelect: doSelect,
onSelectAll: doSelectAll,
}));
</script>
<template>
<Table :childrenRecordName="childrenRecordName" :columns="columns" :dataSource="data" :pagination="false" :rowKey="rowKey" :rowSelection="rowSelection" />
</template>Tree Selection Association (checkRelation)
By setting rowSelection.checkRelation to 'related', you can enable parent-child node selection association. Selecting a parent node automatically selects all child nodes, and selecting a child node affects the parent node's state (checked/half-checked/unchecked).
| Key | 名称 | 数据类型 | 描述 | |
|---|---|---|---|---|
| videos_info | 视频信息 | Object | 视频的元信息 | |
| text_info | 文本信息 | Object | 文本的元信息 |
Code
<script setup lang="ts">
import { computed, ref } from 'vue';
import { Table, type ColumnProps, type RowSelectionProps } from '@fibrous/semi-ui-vue';
interface Row {
key: string;
dataKey: string;
name: string;
type: string;
description: string;
children?: Row[];
}
const selectedRowKeys = ref<(string | number)[]>([]);
const columns: ColumnProps<Row>[] = [
{
title: 'Key',
dataIndex: 'dataKey',
key: 'dataKey',
},
{
title: '名称',
dataIndex: 'name',
key: 'name',
width: 200,
},
{
title: '数据类型',
dataIndex: 'type',
key: 'type',
width: 200,
},
{
title: '描述',
dataIndex: 'description',
key: 'description',
},
];
const data: Row[] = [
{
key: '1',
dataKey: 'videos_info',
name: '视频信息',
type: 'Object',
description: '视频的元信息',
children: [
{
key: '1-1',
dataKey: 'status',
name: '视频状态',
type: 'Enum',
description: '视频的可见状态',
},
{
key: '1-2',
dataKey: 'vid',
name: '视频 ID',
type: 'String',
description: '标识视频的唯一 ID',
children: [
{
key: '1-2-1',
dataKey: 'video_url',
name: '视频地址',
type: 'String',
description: '视频的唯一链接',
},
],
},
],
},
{
key: '2',
dataKey: 'text_info',
name: '文本信息',
type: 'Object',
description: '文本的元信息',
children: [
{
key: '2-1',
dataKey: 'title',
name: '标题',
type: 'String',
description: '文本标题',
},
{
key: '2-2',
dataKey: 'description',
name: '描述',
type: 'String',
description: '文本描述',
},
],
},
];
const rowSelection = computed((): RowSelectionProps<Row> => ({
selectedRowKeys: selectedRowKeys.value,
onChange: (keys) => {
selectedRowKeys.value = keys;
},
checkRelation: 'related',
}));
</script>
<template>
<Table :columns="columns" :dataSource="data" :pagination="false" :rowSelection="rowSelection" />
</template>Custom Row or Cell Events and Properties
- The incoming
onRow/onHeaderRowcan define the native event or property of a table or table header line. - The incoming
Column.onCell/Column.onHeaderCellcan define a table or header cell native event or property.
In principle, the properties or events supported on tr / td / th can be defined, and the returned object uses Vue naming: class, style, data-* and listeners such as onClick, onMouseenter, onDblclick and onContextmenu. A misspelled key is a type error. For example:
- The tr at the head of the table defines
onMouseenter/onMouseleave - The tr of the table defines
class - The third line of the table defines
onClick.
标题 | 所有者 | ||
|---|---|---|---|
| 0 KB | 姜 姜鹏志 | 2024-05-06 | |
| 5 KB | 郝 郝宣 | 2024-05-11 | |
| 10 KB | 姜 姜鹏志 | 2024-05-16 | |
| 15 KB | 郝 郝宣 | 2024-05-21 | |
| 20 KB | 姜 姜鹏志 | 2024-05-26 | |
| 25 KB | 郝 郝宣 | 2024-05-31 | |
| 30 KB | 姜 姜鹏志 | 2024-06-05 | |
| 35 KB | 郝 郝宣 | 2024-06-10 | |
| 40 KB | 姜 姜鹏志 | 2024-06-15 | |
| 45 KB | 郝 郝宣 | 2024-06-20 |
Code
<script setup lang="ts">
import * as dateFns from 'date-fns';
import { Avatar, Table, type ColumnProps, type TableProps } from '@fibrous/semi-ui-vue';
const DAY = 24 * 60 * 60 * 1000;
const figmaIconUrl = '/assets/placeholder/app.svg';
interface Row {
key: string;
name: string;
owner: string;
size: number;
updateTime: number;
avatarBg: 'grey' | 'red';
}
const columns: ColumnProps<Row>[] = [
{
title: '标题',
dataIndex: 'name',
width: 400,
filters: [
{
text: 'Semi Design 设计稿',
value: 'Semi Design 设计稿',
},
{
text: 'Semi D2C 设计稿',
value: 'Semi D2C 设计稿',
},
],
onFilter: (value, record) => record.name.includes(value),
},
{
title: '大小',
dataIndex: 'size',
sorter: (a, b) => (a.size - b.size > 0 ? 1 : -1),
},
{
title: '所有者',
dataIndex: 'owner',
},
{
title: '更新日期',
dataIndex: 'updateTime',
sorter: (a, b) => (a.updateTime - b.updateTime > 0 ? 1 : -1),
},
];
const data: Row[] = [];
for (let i = 0; i < 46; i++) {
const isSemiDesign = i % 2 === 0;
const randomNumber = (i * 1000) % 199;
data.push({
key: '' + i,
name: isSemiDesign ? `Semi Design 设计稿${i}.fig` : `Semi D2C 设计稿${i}.fig`,
owner: isSemiDesign ? '姜鹏志' : '郝宣',
size: randomNumber,
updateTime: new Date(2024, 4, 6, 12).valueOf() + randomNumber * DAY,
avatarBg: isSemiDesign ? 'grey' : 'red',
});
}
const onRow: TableProps<Row>['onRow'] = (record, index) => {
const props = {
class: 'my-tr-class',
};
if (index === 2) {
return {
...props,
onClick: () => console.log('mouse click: ', record, index),
};
}
return props;
};
const onHeaderRow: TableProps<Row>['onHeaderRow'] = (headerColumns, index) => ({
onMouseenter: () => console.log('mouse enter: ', headerColumns, index),
onMouseleave: () => console.log('mouse leave: ', headerColumns, index),
});
</script>
<template>
<Table :columns="columns" :dataSource="data" :onHeaderRow="onHeaderRow" :onRow="onRow">
<template #cell="{ column, record, text }">
<div v-if="column.dataIndex === 'name'">
<Avatar alt="" shape="square" size="small" :src="figmaIconUrl" :style="{ marginRight: '12px' }" />
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'size'">{{ text }} KB</template>
<div v-else-if="column.dataIndex === 'owner'">
<Avatar :color="record.avatarBg" size="small" :style="{ marginRight: '4px' }">
{{ typeof text === 'string' && text.slice(0, 1) }}
</Avatar>
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'updateTime'">
{{ dateFns.format(new Date(text), 'yyyy-MM-dd') }}
</template>
</template>
</Table>
</template>Zebra Pattern Table
Use OnRow to set a background color for each row to create a zebra stripped table.
| 标题 | 大小 | 所有者 | 更新日期 | |
|---|---|---|---|---|
| 2M | 姜 姜鹏志 | 2020-02-02 05:13 | ||
| 2M | 郝 郝宣 | 2020-01-17 05:31 | ||
| 34KB | Z Zoey Edwards | 2020-01-26 11:01 | ||
| 2M | 姜 姜鹏志 | 2020-02-02 05:13 | ||
| 2M | 郝 郝宣 | 2020-01-17 05:31 | ||
| 34KB | Z Zoey Edwards | 2020-01-26 11:01 |
Code
<script setup lang="ts">
import { IconMore } from '@fibrous/semi-icons-vue';
import { Avatar, Table, type ColumnProps, type TableProps } from '@fibrous/semi-ui-vue';
interface Row {
key: string;
name: string;
nameIconSrc: string;
size: string;
owner: string;
updateTime: string;
avatarBg: 'grey' | 'red' | 'light-blue';
}
const columns: ColumnProps<Row>[] = [
{
title: '标题',
dataIndex: 'name',
width: 400,
},
{
title: '大小',
dataIndex: 'size',
},
{
title: '所有者',
dataIndex: 'owner',
},
{
title: '更新日期',
dataIndex: 'updateTime',
},
{
title: '',
dataIndex: 'operate',
},
];
const data: Row[] = [
{
key: '1',
name: 'Semi Design 设计稿.fig',
nameIconSrc: '/assets/placeholder/app.svg',
size: '2M',
owner: '姜鹏志',
updateTime: '2020-02-02 05:13',
avatarBg: 'grey',
},
{
key: '2',
name: 'Semi Design 分享演示文稿',
nameIconSrc: '/assets/docs-icon.png',
size: '2M',
owner: '郝宣',
updateTime: '2020-01-17 05:31',
avatarBg: 'red',
},
{
key: '3',
name: '设计文档',
nameIconSrc: '/assets/docs-icon.png',
size: '34KB',
owner: 'Zoey Edwards',
updateTime: '2020-01-26 11:01',
avatarBg: 'light-blue',
},
{
key: '4',
name: 'Semi D2C 设计稿.fig',
nameIconSrc: '/assets/placeholder/app.svg',
size: '2M',
owner: '姜鹏志',
updateTime: '2020-02-02 05:13',
avatarBg: 'grey',
},
{
key: '5',
name: 'Semi D2C 分享演示文稿',
nameIconSrc: '/assets/docs-icon.png',
size: '2M',
owner: '郝宣',
updateTime: '2020-01-17 05:31',
avatarBg: 'red',
},
{
key: '6',
name: 'Semi D2C 设计文档',
nameIconSrc: '/assets/docs-icon.png',
size: '34KB',
owner: 'Zoey Edwards',
updateTime: '2020-01-26 11:01',
avatarBg: 'light-blue',
},
];
const handleRow: TableProps<Row>['onRow'] = (_record, index) => (index % 2 === 0 ? { style: { background: 'var(--semi-color-fill-0)' } } : {});
</script>
<template>
<Table :columns="columns" :dataSource="data" :onRow="handleRow" :pagination="false">
<template #cell="{ column, text, record }">
<div v-if="column.dataIndex === 'name'">
<Avatar alt="" shape="square" size="small" :src="record.nameIconSrc" :style="{ marginRight: '12px' }" />
{{ text }}
</div>
<div v-else-if="column.dataIndex === 'owner'">
<Avatar :color="record.avatarBg" size="small" :style="{ marginRight: '4px' }">
{{ typeof text === 'string' ? text.slice(0, 1) : '' }}
</Avatar>
{{ text }}
</div>
<IconMore v-else-if="column.dataIndex === 'operate'" />
</template>
</Table>
</template>Custom Header Style
Return a specific style or class through Column.onHeaderCell to customize the header style.
In the example below, the header background color is changed by passing backgroundColor.
| 标题 | 大小 | 所有者 | 更新日期 | |
|---|---|---|---|---|
| 2M | 姜 姜鹏志 | 2020-02-02 05:13 | ||
| 2M | 郝 郝宣 | 2020-01-17 05:31 | ||
| 34KB | Z Zoey Edwards | 2020-01-26 11:01 |
Code
<script setup lang="ts">
import { IconMore } from '@fibrous/semi-icons-vue';
import { Avatar, Table, type ColumnProps } from '@fibrous/semi-ui-vue';
interface Row {
key: string;
name: string;
nameIconSrc: string;
size: string;
owner: string;
updateTime: string;
avatarBg: 'grey' | 'red' | 'light-blue';
}
const onHeaderCell = () => ({
style: {
backgroundColor: 'var(--semi-color-fill-0)',
},
});
const columns: ColumnProps<Row>[] = [
{
title: '标题',
dataIndex: 'name',
width: 280,
},
{
title: '大小',
width: 100,
dataIndex: 'size',
},
{
title: '所有者',
dataIndex: 'owner',
width: 200,
},
{
title: '更新日期',
width: 300,
dataIndex: 'updateTime',
},
{
title: '',
dataIndex: 'operate',
},
].map((column) => ({ ...column, onHeaderCell }));
const data: Row[] = [
{
key: '1',
name: 'Semi Design 设计稿.fig',
nameIconSrc: '/assets/placeholder/app.svg',
size: '2M',
owner: '姜鹏志',
updateTime: '2020-02-02 05:13',
avatarBg: 'grey',
},
{
key: '2',
name: 'Semi Design 分享演示文稿',
nameIconSrc: '/assets/docs-icon.png',
size: '2M',
owner: '郝宣',
updateTime: '2020-01-17 05:31',
avatarBg: 'red',
},
{
key: '3',
name: '设计文档',
nameIconSrc: '/assets/docs-icon.png',
size: '34KB',
owner: 'Zoey Edwards',
updateTime: '2020-01-26 11:01',
avatarBg: 'light-blue',
},
];
</script>
<template>
<Table :columns="columns" :dataSource="data" :pagination="false">
<template #cell="{ column, text, record }">
<div v-if="column.dataIndex === 'name'">
<Avatar alt="" shape="square" size="small" :src="record.nameIconSrc" :style="{ marginRight: '12px' }" />
{{ text }}
</div>
<div v-else-if="column.dataIndex === 'owner'">
<Avatar :color="record.avatarBg" size="small" :style="{ marginRight: '4px' }">
{{ typeof text === 'string' && text.slice(0, 1) }}
</Avatar>
{{ text }}
</div>
<IconMore v-else-if="column.dataIndex === 'operate'" />
</template>
</Table>
</template>Custom Cell Hover Style
Table applies the hover style to the whole row by default. To change it, override the styles with CSS.
In the example below, CSS overrides change the hover background from row highlight to cell highlight.
.component-table-demo-cell-hover-custom {
.semi-table-tbody {
// Remove the original row hover style
.semi-table-row:hover {
.semi-table-row-cell {
background-color: transparent;
background-image: none;
&.semi-table-cell-fixed-left::before {
background-color: transparent;
}
}
// Add a style to a single cell
.semi-table-row-cell:hover {
background-color: var(--semi-light-green-1);
}
}
}
}
| 标题 | 大小 | 所有者 | 更新日期 | |
|---|---|---|---|---|
| 2M | 姜 姜鹏志 | 2020-02-02 05:13 | ||
| 2M | 郝 郝宣 | 2020-01-17 05:31 | ||
| 34KB | Z Zoey Edwards | 2020-01-26 11:01 |
Code
<script setup lang="ts">
import { IconMore } from '@fibrous/semi-icons-vue';
import { Avatar, Table, type ColumnProps } from '@fibrous/semi-ui-vue';
interface Row {
key: string;
name: string;
nameIconSrc: string;
size: string;
owner: string;
updateTime: string;
avatarBg: 'grey' | 'red' | 'light-blue';
}
const columns: ColumnProps<Row>[] = [
{
title: '标题',
dataIndex: 'name',
},
{
title: '大小',
width: 100,
dataIndex: 'size',
},
{
title: '所有者',
dataIndex: 'owner',
width: 200,
},
{
title: '更新日期',
width: 300,
dataIndex: 'updateTime',
},
{
title: '',
dataIndex: 'operate',
},
];
const data: Row[] = [
{
key: '1',
name: 'Semi Design 设计稿.fig',
nameIconSrc: '/assets/placeholder/app.svg',
size: '2M',
owner: '姜鹏志',
updateTime: '2020-02-02 05:13',
avatarBg: 'grey',
},
{
key: '2',
name: 'Semi Design 分享演示文稿',
nameIconSrc: '/assets/docs-icon.png',
size: '2M',
owner: '郝宣',
updateTime: '2020-01-17 05:31',
avatarBg: 'red',
},
{
key: '3',
name: '设计文档',
nameIconSrc: '/assets/docs-icon.png',
size: '34KB',
owner: 'Zoey Edwards',
updateTime: '2020-01-26 11:01',
avatarBg: 'light-blue',
},
];
</script>
<template>
<Table class="component-table-demo-cell-hover-custom" :columns="columns" :dataSource="data" :pagination="false">
<template #cell="{ column, record, text }">
<div v-if="column.dataIndex === 'name'">
<Avatar alt="" shape="square" size="small" :src="record.nameIconSrc" :style="{ marginRight: '12px' }" />
{{ text }}
</div>
<div v-else-if="column.dataIndex === 'owner'">
<Avatar :color="record.avatarBg" size="small" :style="{ marginRight: '4px' }">
{{ typeof text === 'string' && text.slice(0, 1) }}
</Avatar>
{{ text }}
</div>
<IconMore v-else-if="column.dataIndex === 'operate'" />
</template>
</Table>
</template>Column Ellipsis
Use ellipsis to make cells automatically clipped.
| 所有者 | 大小 | 更新日期 | ||
|---|---|---|---|---|
| Semi is designed based on FA architecture, and the main logic is extracted as Foundation package, which is easy to migrate to other frameworks | Pengzhi Jiang Pengzhi Jiang Pengzhi Jiang Pengzhi Jiang | 2M | 2020-02-02 05:13 | |
| 由抖音前端与 UED 团队维护,易于定制的现代化设计系统,帮助设计师与开发者打造高质量产品。由抖音前端与 UED 团队维护,易于定制的现代化设计系统,帮助设计师与开发者打造高质量产品。 | 郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣 | 2M | 2020-02-02 05:13 | |
| Semi is designed based on FA architecture, and the main logic is extracted as Foundation package, which is easy to migrate to other frameworks | Pengzhi Jiang Pengzhi Jiang Pengzhi Jiang Pengzhi Jiang | 34KB | 2020-02-02 05:13 | |
| 由抖音前端与 UED 团队维护,易于定制的现代化设计系统,帮助设计师与开发者打造高质量产品。由抖音前端与 UED 团队维护,易于定制的现代化设计系统,帮助设计师与开发者打造高质量产品。 | 郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣 | 34KB | 2020-02-02 05:13 |
Code
<script setup lang="ts">
import { IconMore } from '@fibrous/semi-icons-vue';
import { Table, type ColumnProps } from '@fibrous/semi-ui-vue';
const columns: ColumnProps[] = [
{
title: '标题',
dataIndex: 'name',
fixed: true,
width: 250,
filters: [
{
text: 'Semi Design 设计稿',
value: 'Semi Design 设计稿',
},
{
text: 'Semi D2C 设计稿',
value: 'Semi D2C 设计稿',
},
],
onFilter: (value, record) => record.name.includes(value),
sorter: (a, b) => (a.name.length - b.name.length > 0 ? 1 : -1),
ellipsis: true,
},
{
title: '所有者',
dataIndex: 'owner',
width: 200,
ellipsis: true,
},
{
title: '大小',
dataIndex: 'size',
ellipsis: true,
},
{
title: '更新日期',
dataIndex: 'updateTime',
width: 200,
ellipsis: true,
},
{
title: '',
dataIndex: 'operate',
fixed: 'right',
align: 'center',
width: 100,
},
];
const data = [
{
key: '1',
name: 'Semi is designed based on FA architecture, and the main logic is extracted as Foundation package, which is easy to migrate to other frameworks',
nameIconSrc: '/assets/placeholder/app.svg',
size: '2M',
owner: 'Pengzhi Jiang Pengzhi Jiang Pengzhi Jiang Pengzhi Jiang',
updateTime: '2020-02-02 05:13',
avatarBg: 'grey',
},
{
key: '2',
name: '由抖音前端与 UED 团队维护,易于定制的现代化设计系统,帮助设计师与开发者打造高质量产品。由抖音前端与 UED 团队维护,易于定制的现代化设计系统,帮助设计师与开发者打造高质量产品。',
nameIconSrc: '/assets/docs-icon.png',
size: '2M',
owner: '郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣',
updateTime: '2020-02-02 05:13',
avatarBg: 'red',
},
{
key: '3',
nameIconSrc: '/assets/docs-icon.png',
name: 'Semi is designed based on FA architecture, and the main logic is extracted as Foundation package, which is easy to migrate to other frameworks',
size: '34KB',
owner: 'Pengzhi Jiang Pengzhi Jiang Pengzhi Jiang Pengzhi Jiang',
updateTime: '2020-02-02 05:13',
avatarBg: 'light-blue',
},
{
key: '4',
name: '由抖音前端与 UED 团队维护,易于定制的现代化设计系统,帮助设计师与开发者打造高质量产品。由抖音前端与 UED 团队维护,易于定制的现代化设计系统,帮助设计师与开发者打造高质量产品。',
nameIconSrc: '/assets/docs-icon.png',
size: '34KB',
owner: '郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣',
updateTime: '2020-02-02 05:13',
avatarBg: 'light-blue',
},
];
const scroll = { x: 1200 };
</script>
<template>
<Table :columns="columns" :dataSource="data" :pagination="false" :scroll="scroll">
<template #cell="{ column }">
<IconMore v-if="column.dataIndex === 'operate'" />
</template>
</Table>
</template>Set ellipsis.showTitle to false to hide the default native HTML title. With the #cell slot you can customize the content prompt.
| 所有者 | 大小 | 更新日期 | ||
|---|---|---|---|---|
| Semi is designed based on FA architecture, and the main logic is extracted as Foundation package, which is easy to migrate to other frameworks | Pengzhi Jiang Pengzhi Jiang Pengzhi Jiang Pengzhi Jiang | 2M | 2020-02-02 05:13 | |
| 由抖音前端与 UED 团队维护,易于定制的现代化设计系统,帮助设计师与开发者打造高质量产品。由抖音前端与 UED 团队维护,易于定制的现代化设计系统,帮助设计师与开发者打造高质量产品。 | 郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣 | 2M | 2020-02-02 05:13 | |
| Semi is designed based on FA architecture, and the main logic is extracted as Foundation package, which is easy to migrate to other frameworks | Pengzhi Jiang | 34KB | 2020-02-02 05:13 | |
| 由抖音前端与 UED 团队维护,易于定制的现代化设计系统,帮助设计师与开发者打造高质量产品。由抖音前端与 UED 团队维护,易于定制的现代化设计系统,帮助设计师与开发者打造高质量产品。 | 郝宣 | 34KB | 2020-02-02 05:13 |
Code
<script setup lang="ts">
import { IconMore } from '@fibrous/semi-icons-vue';
import { Table, Typography, type ColumnProps } from '@fibrous/semi-ui-vue';
const columns: ColumnProps[] = [
{
title: '标题',
dataIndex: 'name',
fixed: true,
width: 250,
filters: [
{
text: 'Semi Design 设计稿',
value: 'Semi Design 设计稿',
},
{
text: 'Semi D2C 设计稿',
value: 'Semi D2C 设计稿',
},
],
onFilter: (value, record) => record.name.includes(value),
sorter: (a, b) => (a.name.length - b.name.length > 0 ? 1 : -1),
ellipsis: { showTitle: false },
},
{
title: '所有者',
dataIndex: 'owner',
width: 200,
ellipsis: { showTitle: false },
},
{
title: '大小',
dataIndex: 'size',
ellipsis: true,
},
{
title: '更新日期',
dataIndex: 'updateTime',
width: 200,
ellipsis: true,
},
{
title: '',
dataIndex: 'operate',
fixed: 'right',
align: 'center',
width: 100,
},
];
const data = [
{
key: '1',
name: 'Semi is designed based on FA architecture, and the main logic is extracted as Foundation package, which is easy to migrate to other frameworks',
nameIconSrc: '/assets/placeholder/app.svg',
size: '2M',
owner: 'Pengzhi Jiang Pengzhi Jiang Pengzhi Jiang Pengzhi Jiang',
updateTime: '2020-02-02 05:13',
avatarBg: 'grey',
},
{
key: '2',
name: '由抖音前端与 UED 团队维护,易于定制的现代化设计系统,帮助设计师与开发者打造高质量产品。由抖音前端与 UED 团队维护,易于定制的现代化设计系统,帮助设计师与开发者打造高质量产品。',
nameIconSrc: '/assets/docs-icon.png',
size: '2M',
owner: '郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣郝宣',
updateTime: '2020-02-02 05:13',
avatarBg: 'red',
},
{
key: '3',
nameIconSrc: '/assets/docs-icon.png',
name: 'Semi is designed based on FA architecture, and the main logic is extracted as Foundation package, which is easy to migrate to other frameworks',
size: '34KB',
owner: 'Pengzhi Jiang',
updateTime: '2020-02-02 05:13',
avatarBg: 'light-blue',
},
{
key: '4',
name: '由抖音前端与 UED 团队维护,易于定制的现代化设计系统,帮助设计师与开发者打造高质量产品。由抖音前端与 UED 团队维护,易于定制的现代化设计系统,帮助设计师与开发者打造高质量产品。',
nameIconSrc: '/assets/docs-icon.png',
size: '34KB',
owner: '郝宣',
updateTime: '2020-02-02 05:13',
avatarBg: 'light-blue',
},
];
const scroll = { x: 1200 };
</script>
<template>
<Table :columns="columns" :dataSource="data" :pagination="false" :scroll="scroll">
<template #cell="{ column, text }">
<Typography.Text v-if="column.dataIndex === 'name' || column.dataIndex === 'owner'" :ellipsis="{ showTooltip: true }">
{{ text }}
</Typography.Text>
<IconMore v-else-if="column.dataIndex === 'operate'" />
</template>
</Table>
</template>Resizable Column
Basic Resizable Column
For some columns with more content, you can choose to turn on the telescopic column function and pull and pull at the head to realize the real-time change of column width.
But you need to pay attention to some parameters:
resizableis set totrueor anobject- Any column in
columnsthat requires a telescopic function should specify thewidthfield (if not passed, the column does not have a telescopic function and its column width will be automatically adjusted by the browser) column.resizecan take effect after resizable is enabled. After setting to false, the column no longer supports scaling.- A column that has been dragged keeps its dragged width, while columns that have not been dragged follow the
widthincolumns
When used with fixed columns, you need to specify a column without setting the width
It is not recommended to use it with
scroll.xat the same time. scroll.x specifies that the table has a width range, and stretching columns will expand the column width, which may cause the table to be misaligned
标题 | 所有者 | 操作列 | ||
|---|---|---|---|---|
| 0 KB | 姜 姜鹏志 | 2024-05-06 | ||
| 5 KB | 郝 郝宣 | 2024-05-11 | ||
| 10 KB | 姜 姜鹏志 | 2024-05-16 | ||
| 15 KB | 郝 郝宣 | 2024-05-21 | ||
| 20 KB | 姜 姜鹏志 | 2024-05-26 | ||
| 25 KB | 郝 郝宣 | 2024-05-31 | ||
| 30 KB | 姜 姜鹏志 | 2024-06-05 | ||
| 35 KB | 郝 郝宣 | 2024-06-10 | ||
| 40 KB | 姜 姜鹏志 | 2024-06-15 | ||
| 45 KB | 郝 郝宣 | 2024-06-20 |
Code
<script setup lang="ts">
import * as dateFns from 'date-fns';
import { IconMore } from '@fibrous/semi-icons-vue';
import { Avatar, Table, type ColumnProps } from '@fibrous/semi-ui-vue';
const DAY = 24 * 60 * 60 * 1000;
const figmaIconUrl = '/assets/placeholder/app.svg';
interface Row {
key: string;
name: string;
owner: string;
size: number;
updateTime: number;
avatarBg: 'grey' | 'red';
}
const columns: ColumnProps<Row>[] = [
{
title: '标题',
dataIndex: 'name',
width: 300,
resize: false,
filters: [
{
text: 'Semi Design 设计稿',
value: 'Semi Design 设计稿',
},
{
text: 'Semi D2C 设计稿',
value: 'Semi D2C 设计稿',
},
],
onFilter: (value, record) => record.name.includes(value),
},
{
title: '大小',
dataIndex: 'size',
width: 200,
sorter: (a, b) => (a.size - b.size > 0 ? 1 : -1),
},
{
title: '所有者',
width: 200,
dataIndex: 'owner',
},
{
title: '更新日期',
dataIndex: 'updateTime',
sorter: (a, b) => (a.updateTime - b.updateTime > 0 ? 1 : -1),
},
{
title: '操作列',
dataIndex: 'operate',
fixed: 'right',
width: 100,
resize: false,
},
];
const data: Row[] = [];
for (let i = 0; i < 46; i++) {
const isSemiDesign = i % 2 === 0;
const randomNumber = (i * 1000) % 199;
data.push({
key: '' + i,
name: isSemiDesign ? `Semi Design 设计稿${i}.fig` : `Semi D2C 设计稿${i}.fig`,
owner: isSemiDesign ? '姜鹏志' : '郝宣',
size: randomNumber,
updateTime: new Date(2024, 4, 6, 12).valueOf() + randomNumber * DAY,
avatarBg: isSemiDesign ? 'grey' : 'red',
});
}
</script>
<template>
<Table bordered :columns="columns" :dataSource="data" resizable>
<template #cell="{ column, record, text }">
<div v-if="column.dataIndex === 'name'">
<Avatar alt="" shape="square" size="small" :src="figmaIconUrl" :style="{ marginRight: '12px' }" />
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'size'">{{ text }} KB</template>
<div v-else-if="column.dataIndex === 'owner'">
<Avatar :color="record.avatarBg" size="small" :style="{ marginRight: '4px' }">
{{ typeof text === 'string' && text.slice(0, 1) }}
</Avatar>
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'updateTime'">
{{ dateFns.format(new Date(text), 'yyyy-MM-dd') }}
</template>
<IconMore v-else-if="column.dataIndex === 'operate'" />
</template>
</Table>
</template>Advanced Telescopic Columns
resizable can also be an object, including three event methods:
- onResize
- onResizeStart
- onResizeStop
These three callback will be triggered on changing column width, start changing column width and stop changing column width respectively. Developers can choose to modify the column at this time, such as adding a vertical line effect when dragging, as shown below.
标题 | 所有者 | ||
|---|---|---|---|
| 0 KB | 姜 姜鹏志 | 2024-05-06 | |
| 5 KB | 郝 郝宣 | 2024-05-11 | |
| 10 KB | 姜 姜鹏志 | 2024-05-16 | |
| 15 KB | 郝 郝宣 | 2024-05-21 | |
| 20 KB | 姜 姜鹏志 | 2024-05-26 |
Code
<script setup lang="ts">
import { normalizeClass } from 'vue';
import * as dateFns from 'date-fns';
import { addClass, removeClass } from '@fibrous/semi-foundation/utils/classnames';
import { Avatar, Table, type ColumnProps, type TableResizableProps } from '@fibrous/semi-ui-vue';
const DAY = 24 * 60 * 60 * 1000;
const figmaIconUrl = '/assets/placeholder/app.svg';
const pagination = { pageSize: 5 };
interface Row {
key: string;
name: string;
owner: string;
size: number;
updateTime: number;
avatarBg: 'grey' | 'red';
}
const columns: ColumnProps<Row>[] = [
{
title: '标题',
dataIndex: 'name',
width: 400,
filters: [
{
text: 'Semi Design 设计稿',
value: 'Semi Design 设计稿',
},
{
text: 'Semi D2C 设计稿',
value: 'Semi D2C 设计稿',
},
],
onFilter: (value, record) => record.name.includes(value),
},
{
title: '大小',
dataIndex: 'size',
width: 200,
sorter: (a, b) => (a.size - b.size > 0 ? 1 : -1),
},
{
title: '所有者',
width: 200,
dataIndex: 'owner',
},
{
title: '更新日期',
dataIndex: 'updateTime',
sorter: (a, b) => (a.updateTime - b.updateTime > 0 ? 1 : -1),
},
];
const data: Row[] = [];
for (let i = 0; i < 46; i++) {
const isSemiDesign = i % 2 === 0;
const randomNumber = (i * 1000) % 199;
data.push({
key: '' + i,
name: isSemiDesign ? `Semi Design 设计稿${i}.fig` : `Semi D2C 设计稿${i}.fig`,
owner: isSemiDesign ? '姜鹏志' : '郝宣',
size: randomNumber,
updateTime: new Date(2024, 4, 6, 12).valueOf() + randomNumber * DAY,
avatarBg: isSemiDesign ? 'grey' : 'red',
});
}
const resizable: TableResizableProps<Row> = {
onResizeStart: (curColumn) => ({ class: addClass(normalizeClass(curColumn.class), 'my-resizing') }),
onResizeStop: (curColumn) => ({ class: removeClass(normalizeClass(curColumn.class), 'my-resizing') }),
};
</script>
<template>
<div id="components-table-demo-resizable-column">
<Table bordered :columns="columns" :dataSource="data" :pagination="pagination" :resizable="resizable">
<template #cell="{ column, record, text }">
<div v-if="column.dataIndex === 'name'">
<Avatar alt="" shape="square" size="small" :src="figmaIconUrl" :style="{ marginRight: '12px' }" />
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'size'">{{ text }} KB</template>
<div v-else-if="column.dataIndex === 'owner'">
<Avatar :color="record.avatarBg" size="small" :style="{ marginRight: '4px' }">
{{ typeof text === 'string' && text.slice(0, 1) }}
</Avatar>
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'updateTime'">
{{ dateFns.format(new Date(text), 'yyyy-MM-dd') }}
</template>
</template>
</Table>
</div>
</template>The CSS style definition used in this example:
#components-table-demo-resizable-column .my-resizing {
border-right: 2px solid red;
}
#components-table-demo-resizable-column .semi-table-resize-handle:hover {
background-color: red;
}
#components-table-demo-resizable-column .my-resizing:hover .semi-table-resize-handle {
background-color: inherit;
}
Drag Sorting
Use @dnd-kit/vue from dnd-kit with the components prop to easily implement drag-and-drop sorting: pass a Vue component as components.body.row, it receives the attributes and listeners of every data row (including data-row-key), and calls useSortable inside.
标题 | 所有者 | ||
|---|---|---|---|
| 0 KB | 姜 姜鹏志 | 2024-05-06 | |
| 5 KB | 郝 郝宣 | 2024-05-06 | |
| 10 KB | 姜 姜鹏志 | 2024-05-06 | |
| 15 KB | 郝 郝宣 | 2024-05-06 | |
| 20 KB | 姜 姜鹏志 | 2024-05-06 | |
| 25 KB | 郝 郝宣 | 2024-05-06 | |
| 30 KB | 姜 姜鹏志 | 2024-05-06 | |
| 35 KB | 郝 郝宣 | 2024-05-06 | |
| 40 KB | 姜 姜鹏志 | 2024-05-06 | |
| 45 KB | 郝 郝宣 | 2024-05-06 |
Code
<script setup lang="ts">
import { computed, defineComponent, h, shallowRef } from 'vue';
import { RestrictToVerticalAxis } from '@dnd-kit/abstract/modifiers';
import { Accessibility } from '@dnd-kit/dom';
import { arrayMove } from '@dnd-kit/helpers';
import { DragDropProvider, type DragDropProviderProps, type DragEndEvent } from '@dnd-kit/vue';
import { isSortable, useSortable } from '@dnd-kit/vue/sortable';
import * as dateFns from 'date-fns';
import { Avatar, Table, type ColumnProps, type TableChangeInfo } from '@fibrous/semi-ui-vue';
const figmaIconUrl = '/assets/placeholder/app.svg';
interface Row {
key: string;
name: string;
owner: string;
size: number;
updateTime: number;
avatarBg: 'grey' | 'red';
}
const getData = () => {
const data: Row[] = [];
for (let i = 0; i < 46; i++) {
const isSemiDesign = i % 2 === 0;
const randomNumber = (i * 1000) % 199;
data.push({
key: '' + i,
name: isSemiDesign ? `Semi Design 设计稿${i}.fig` : `Semi D2C 设计稿${i}.fig`,
owner: isSemiDesign ? '姜鹏志' : '郝宣',
size: randomNumber,
updateTime: new Date(2024, 4, 6, 12).valueOf() + randomNumber,
avatarBg: isSemiDesign ? 'grey' : 'red',
});
}
return data;
};
const pageSize = 10;
const dataSource = shallowRef(getData());
const pageNum = shallowRef(1);
const pageData = computed(() => dataSource.value.slice((pageNum.value - 1) * pageSize, pageNum.value * pageSize));
const columns: ColumnProps<Row>[] = [
{
title: '标题',
dataIndex: 'name',
width: 400,
filters: [
{
text: 'Semi Design 设计稿',
value: 'Semi Design 设计稿',
},
{
text: 'Semi D2C 设计稿',
value: 'Semi D2C 设计稿',
},
],
onFilter: (value, record) => record.name.includes(value),
},
{
title: '大小',
dataIndex: 'size',
sorter: (a, b) => (a.size - b.size > 0 ? 1 : -1),
},
{
title: '所有者',
dataIndex: 'owner',
},
{
title: '更新日期',
dataIndex: 'updateTime',
sorter: (a, b) => (a.updateTime - b.updateTime > 0 ? 1 : -1),
},
];
// Table creates a body row component per row and passes it the row's attributes, so the sortable must be set up
// inside it. A demo is a single SFC, hence the component is defined here.
const SortableRow = defineComponent((_props, { attrs, slots }) => {
const element = shallowRef<HTMLElement | null>(null);
// The sortable index is relative to the current page
const { isDragging } = useSortable({
id: () => String(attrs['data-row-key']),
index: () => pageData.value.findIndex((row) => row.key === attrs['data-row-key']),
element,
});
return () =>
h(
'tr',
{
ref: element,
class: { isDragging: isDragging.value },
style: {
cursor: 'grabbing',
...(isDragging.value ? { zIndex: 999, position: 'relative' as const } : {}),
},
},
slots.default?.()
);
});
const components = { body: { row: SortableRow } };
// Accessibility would add role="button" and a Tab stop to each row; keep table row semantics
const plugins: DragDropProviderProps['plugins'] = (defaults) => defaults.filter((plugin) => plugin !== Accessibility);
const modifiers = [RestrictToVerticalAxis];
const handleDragEnd = (event: DragEndEvent) => {
const { source } = event.operation;
if (event.canceled || !isSortable(source) || source.initialIndex === source.index) {
return;
}
const offset = (pageNum.value - 1) * pageSize;
dataSource.value = arrayMove(dataSource.value, offset + source.initialIndex, offset + source.index);
};
const handleChange = ({ pagination }: TableChangeInfo<Row>) => {
if (pagination?.currentPage) {
pageNum.value = pagination.currentPage;
}
};
</script>
<template>
<DragDropProvider :modifiers="modifiers" :plugins="plugins" @dragEnd="handleDragEnd">
<Table :columns="columns" :components="components" :dataSource="pageData" :pagination="{ currentPage: pageNum, pageSize, total: dataSource.length }" rowKey="key" @change="handleChange">
<template #cell="{ column, record, text }">
<div v-if="column.dataIndex === 'name'">
<Avatar alt="" shape="square" size="small" :src="figmaIconUrl" :style="{ marginRight: '12px' }" />
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'size'">{{ text }} KB</template>
<div v-else-if="column.dataIndex === 'owner'">
<Avatar :color="record.avatarBg" size="small" :style="{ marginRight: '4px' }">
{{ typeof text === 'string' && text.slice(0, 1) }}
</Avatar>
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'updateTime'">
{{ dateFns.format(new Date(text), 'yyyy-MM-dd') }}
</template>
</template>
</Table>
</DragDropProvider>
</template>Table Grouping
For some tables whose data needs to be displayed in groups, you can pass in groupBy to define the grouping rules, and use the #groupSection slot (parameters groupKey and group) to define the rendering of the grouping table header; the column configuration of the only column of a group row is returned by groupSectionColumn.
Note: Be sure to provide a "key" for each row of data that is different from other row values, or use the rowKey parameter to specify a property name as the primary key.
标题 | 所有者 |
|---|
| 100 KB | 姜 姜鹏志 | 2024-08-14 | |
| 100 KB | 郝 郝宣 | 2024-08-14 | |
| 100 KB | 姜 姜鹏志 | 2024-08-14 | |
| 112 KB | 郝 郝宣 | 2024-08-26 | |
| 112 KB | 姜 姜鹏志 | 2024-08-26 | |
| 112 KB | 郝 郝宣 | 2024-08-26 | |
| 105 KB | 姜 姜鹏志 | 2024-08-19 | |
| 105 KB | 郝 郝宣 | 2024-08-19 | |
| 105 KB | 姜 姜鹏志 | 2024-08-19 | |
| 117 KB | 郝 郝宣 | 2024-08-31 |
Code
<script setup lang="ts">
import * as dateFns from 'date-fns';
import { Avatar, Table, type ColumnProps } from '@fibrous/semi-ui-vue';
const DAY = 24 * 60 * 60 * 1000;
const figmaIconUrl = '/assets/placeholder/app.svg';
interface Row {
key: string;
name: string;
owner: string;
size: number;
updateTime: number;
avatarBg: 'grey' | 'red';
}
const columns: ColumnProps<Row>[] = [
{
title: '标题',
dataIndex: 'name',
width: 400,
filters: [
{
text: 'Semi Design 设计稿',
value: 'Semi Design 设计稿',
},
{
text: 'Semi D2C 设计稿',
value: 'Semi D2C 设计稿',
},
],
onFilter: (value, record) => record.name.includes(value),
},
{
title: '大小',
dataIndex: 'size',
sorter: (a, b) => (a.size - b.size > 0 ? 1 : -1),
},
{
title: '所有者',
dataIndex: 'owner',
},
{
title: '更新日期',
dataIndex: 'updateTime',
sorter: (a, b) => (a.updateTime - b.updateTime > 0 ? 1 : -1),
},
];
const getData = () => {
const data: Row[] = [];
for (let i = 0; i < 46; i++) {
const isSemiDesign = i % 2 === 0;
const randomNumber = ((i * 1000) % 19) + 100;
data.push({
key: '' + i,
name: isSemiDesign ? `Semi Design 设计稿${i}.fig` : `Semi D2C 设计稿${i}.fig`,
owner: isSemiDesign ? '姜鹏志' : '郝宣',
size: randomNumber,
updateTime: new Date(2024, 4, 6, 12).valueOf() + randomNumber * DAY,
avatarBg: isSemiDesign ? 'grey' : 'red',
});
}
return data;
};
const data = getData();
const scroll = { y: 480 };
const rowKey = (record: Row) => `${record.owner.toLowerCase()}-${record.name.toLowerCase()}`;
const onGroupedRow = (group: { groupKey: string | number; records: Row[] }, index: number) => ({
onClick: () => {
console.log(`Grouped row clicked: `, group, index);
},
});
</script>
<template>
<div :style="{ padding: '20px 0px' }">
<!-- clickGroupedRowToExpand: a click anywhere on the group row expands it -->
<Table clickGroupedRowToExpand :columns="columns" :dataSource="data" groupBy="size" :onGroupedRow="onGroupedRow" :rowKey="rowKey" :scroll="scroll">
<template #groupSection="{ groupKey }">
<strong>根据文件大小分组 {{ groupKey }} KB</strong>
</template>
<template #cell="{ column, text, record }">
<div v-if="column.dataIndex === 'name'">
<Avatar alt="" shape="square" size="small" :src="figmaIconUrl" :style="{ marginRight: '12px' }" />
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'size'">{{ text }} KB</template>
<div v-else-if="column.dataIndex === 'owner'">
<Avatar :color="record.avatarBg" size="small" :style="{ marginRight: '4px' }">
{{ typeof text === 'string' && text.slice(0, 1) }}
</Avatar>
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'updateTime'">
{{ dateFns.format(new Date(text), 'yyyy-MM-dd') }}
</template>
</template>
</Table>
</div>
</template>Virtualized Table
Virtualization can be used for scenes that need to render large-scale data. You can enable this feature by configuring the virtualized parameter. have to be aware of is:
- Must pass
scroll.y(number); the table width comes fromstyle.width, or fromscroll.xwhen it is not set.styleis a style passed through to the root element, so writewidthas a string with a unit, such as'750px';
- Need to pass the height of each line
virtualized.itemSize(when not passed, the default row height followssize:53fordefault,45formiddleand37forsmall, and a group header row is as high as a normal row), can be of the following types:number(index, { sectionRow?: boolean, expandedRow?: boolean }) => number
- Table grouping virtualization is supported.
- The
virtualizedobject also takesoverscanCount: the number of rows rendered above and below the visible area, 2 by default
Call scrollTo(offset) and scrollToItem(index, align) through the component ref of Table, where align is auto (default), smart, center, start or end; calling them on a table without virtualization prints a warning in development.
The following is an example of rendering 1000 pieces of data.
标题 | 所有者 |
|---|
Code
<script setup lang="ts">
import { useTemplateRef } from 'vue';
import * as dateFns from 'date-fns';
import { Avatar, Button, Table, type ColumnProps, type TableHandle } from '@fibrous/semi-ui-vue';
const DAY = 24 * 60 * 60 * 1000;
interface Row {
key: string;
name: string;
owner: string;
size: number;
updateTime: number;
avatarBg: 'grey' | 'red';
}
const columns: ColumnProps<Row>[] = [
{
title: '标题',
dataIndex: 'name',
width: 200,
fixed: true,
filters: [
{
text: 'Semi Design 设计稿',
value: 'Semi Design 设计稿',
},
{
text: 'Semi D2C 设计稿',
value: 'Semi D2C 设计稿',
},
],
onFilter: (value, record) => record.name.includes(value),
},
{
title: '大小',
dataIndex: 'size',
width: 150,
sorter: (a, b) => (a.size - b.size > 0 ? 1 : -1),
},
{
title: '所有者',
dataIndex: 'owner',
},
{
title: '更新日期',
dataIndex: 'updateTime',
fixed: 'right',
width: 150,
sorter: (a, b) => (a.updateTime - b.updateTime > 0 ? 1 : -1),
},
];
const getData = () => {
const data: Row[] = [];
for (let i = 0; i < 1000; i++) {
const isSemiDesign = i % 2 === 0;
const randomNumber = (i * 1000) % 199;
data.push({
key: '' + i,
name: isSemiDesign ? `Semi Design 设计稿${i}.fig` : `Semi D2C 设计稿${i}.fig`,
owner: isSemiDesign ? '姜鹏志' : '郝宣',
size: randomNumber,
updateTime: new Date(2024, 4, 6, 12).valueOf() + randomNumber * DAY,
avatarBg: isSemiDesign ? 'grey' : 'red',
});
}
return data;
};
const data = getData();
const scroll = { y: 400, x: 900 };
const style = { width: '750px', margin: '0 auto' };
const table = useTemplateRef<TableHandle<Row>>('table');
</script>
<template>
<Button @click="table?.scrollToItem(100)">Scroll to 100</Button>
<Table ref="table" :columns="columns" :dataSource="data" :pagination="false" :scroll="scroll" :style="style" virtualized>
<template #cell="{ column, text, record }">
<template v-if="column.dataIndex === 'size'">{{ text }} KB</template>
<div v-else-if="column.dataIndex === 'owner'">
<Avatar :color="record.avatarBg" size="small" :style="{ marginRight: '4px' }">
{{ typeof text === 'string' ? text.slice(0, 1) : '' }}
</Avatar>
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'updateTime'">{{ dateFns.format(new Date(text), 'yyyy-MM-dd') }}</template>
</template>
</Table>
</template>Infinite Scroll
Based on the virtualization feature, we can achieve infinite scroll loading data by listening to the @scroll event. Its parameter holds scrollDirection, scrollOffset and scrollUpdateWasRequested, and it fires only when the vertical scroll offset changes.
标题 | 所有者 |
|---|
Code
<script setup lang="ts">
import { shallowRef } from 'vue';
import * as dateFns from 'date-fns';
import { Avatar, Table, type ColumnProps, type TableVirtualizedProps } from '@fibrous/semi-ui-vue';
const DAY = 24 * 60 * 60 * 1000;
interface Row {
key: string;
name: string;
owner: string;
size: number;
updateTime: number;
avatarBg: 'grey' | 'red';
}
const columns: ColumnProps<Row>[] = [
{
title: '标题',
dataIndex: 'name',
width: 200,
fixed: true,
filters: [
{
text: 'Semi Design 设计稿',
value: 'Semi Design 设计稿',
},
{
text: 'Semi D2C 设计稿',
value: 'Semi D2C 设计稿',
},
],
onFilter: (value, record) => record.name.includes(value),
},
{
title: '大小',
dataIndex: 'size',
width: 150,
sorter: (a, b) => (a.size - b.size > 0 ? 1 : -1),
},
{
title: '所有者',
dataIndex: 'owner',
},
{
title: '更新日期',
dataIndex: 'updateTime',
fixed: 'right',
width: 150,
sorter: (a, b) => (a.updateTime - b.updateTime > 0 ? 1 : -1),
},
];
const pageSize = 20; // 每次加载 20 条
const getPage = (start: number) => {
const page: Row[] = [];
for (let i = start; i < start + pageSize; i++) {
const isSemiDesign = i % 2 === 0;
const randomNumber = (i * 1000) % 199;
page.push({
key: '' + i,
name: isSemiDesign ? `Semi Design 设计稿${i}.fig` : `Semi D2C 设计稿${i}.fig`,
owner: isSemiDesign ? '姜鹏志' : '郝宣',
size: randomNumber,
updateTime: new Date(2024, 4, 6, 12).valueOf() + randomNumber * DAY,
avatarBg: isSemiDesign ? 'grey' : 'red',
});
}
return page;
};
const data = shallowRef(getPage(0));
const scroll = { y: 600, x: 1000 };
const style = { width: '750px', margin: '0 auto' };
const itemSize = 56;
const virtualized: TableVirtualizedProps = { itemSize };
const loadMore = () => {
data.value = [...data.value, ...getPage(data.value.length)];
};
const onScroll = ({ scrollDirection, scrollOffset, scrollUpdateWasRequested }: { scrollDirection: 'forward' | 'backward'; scrollOffset: number; scrollUpdateWasRequested: boolean }) => {
if (scrollDirection === 'forward' && scrollOffset >= (data.value.length - Math.ceil(scroll.y / itemSize) * 1.5) * itemSize && !scrollUpdateWasRequested) {
loadMore();
}
};
</script>
<template>
<Table :columns="columns" :dataSource="data" :pagination="false" :scroll="scroll" :style="style" :virtualized="virtualized" @scroll="onScroll">
<template #cell="{ column, text, record }">
<div v-if="column.dataIndex === 'name'">{{ text }}</div>
<template v-else-if="column.dataIndex === 'size'">{{ text }} KB</template>
<div v-else-if="column.dataIndex === 'owner'">
<Avatar :color="record.avatarBg" size="small" :style="{ marginRight: '4px' }">
{{ typeof text === 'string' && text.slice(0, 1) }}
</Avatar>
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'updateTime'">
{{ dateFns.format(new Date(text), 'yyyy-MM-dd') }}
</template>
</template>
</Table>
</template>Controlled Dynamic Tables
标题 | 所有者 |
|---|
Code
<script setup lang="ts">
import { computed, onMounted, ref, shallowRef } from 'vue';
import * as dateFns from 'date-fns';
import { Avatar, Button, ButtonGroup, Switch, Table, type ColumnProps, type RowSelectionProps, type TableChangeInfo, type TablePaginationPosition, type TablePaginationProps, type TableScroll } from '@fibrous/semi-ui-vue';
interface Row {
key: string;
name: string;
owner: string;
size: number;
updateTime: number;
avatarBg: string;
description?: string;
}
interface PageState extends TablePaginationProps {
currentPage: number;
pageSize: number;
total: number;
}
interface FetchResult {
dataSource: Row[];
pagination: PageState;
sorter: ColumnProps;
filters: ColumnProps[];
}
interface SwitchItem {
text: string;
/** Absent: the switch keeps its own state */
checked?: () => boolean;
onChange: (checked: boolean) => void;
}
const DAY = 24 * 60 * 60 * 1000;
const figmaIconUrl = '/assets/placeholder/app.svg';
const dataTotalSize = 46;
const wrapStyle = { marginBottom: '15px', display: 'flex', justifyContent: 'space-around', flexWrap: 'wrap' } as const;
const switchStyle = { display: 'inline-flex', alignItems: 'center', margin: '5px' };
const initialColumns: ColumnProps[] = [
{
title: '标题',
dataIndex: 'name',
width: 400,
filters: [
{
text: 'Semi Design 设计稿',
value: 'Semi Design 设计稿',
},
{
text: 'Semi D2C 设计稿',
value: 'Semi D2C 设计稿',
},
],
onFilter: (value, record) => record.name.includes(value),
},
{
title: '大小',
dataIndex: 'size',
sorter: (a, b) => (a.size - b.size > 0 ? 1 : -1),
},
{
title: '所有者',
dataIndex: 'owner',
},
{
title: '更新日期',
dataIndex: 'updateTime',
sorter: (a, b) => (a.updateTime - b.updateTime > 0 ? 1 : -1),
},
];
const allData = Array.from({ length: dataTotalSize }, (_v, i): Row => {
const isSemiDesign = i % 2 === 0;
const randomNumber = (i * 1000) % 199;
return {
key: '' + i,
name: isSemiDesign ? `Semi Design 设计稿${i}.fig` : `Semi D2C 设计稿${i}.fig`,
owner: isSemiDesign ? '姜鹏志' : '郝宣',
size: randomNumber,
updateTime: new Date(2024, 4, 6, 12).valueOf() + randomNumber * DAY,
avatarBg: isSemiDesign ? 'grey' : 'red',
description: `这是第 ${i} 份设计稿的详细说明。`,
};
});
const defaultPagination: PageState = {
currentPage: 1,
pageSize: 8,
total: allData.length,
};
const mergeColumns = (column: ColumnProps, columns: ColumnProps[], keys: (keyof ColumnProps)[] = ['dataIndex']) => {
const nextColumns = [...columns];
nextColumns.forEach((curColumn, index) => {
let isTarget = !!(keys && keys.length);
for (const key of keys) {
if (column[key] !== curColumn[key]) {
isTarget = false;
break;
}
}
if (isTarget) {
nextColumns[index] = { ...curColumn, ...column };
}
});
return nextColumns;
};
const filterData = (filters: ColumnProps[], dataSource: Row[]) => {
let result = [...dataSource];
filters.forEach((filter) => {
const filteredValue = filter.filteredValue;
const dataIndex = filter.dataIndex;
if (Array.isArray(filteredValue) && filteredValue.length && dataIndex) {
result = result.filter((data) => filteredValue.filter((value) => String(data[dataIndex as keyof Row]).indexOf(value) > -1).length);
}
});
return result;
};
const sortData = (sortObj: ColumnProps, dataSource: Row[]) => {
const { sortOrder, dataIndex = '' } = sortObj;
let sorter = sortObj.sorter;
let result = dataSource;
if (sorter && sortOrder && typeof sorter !== 'function') {
sorter = (a, b) => (a[dataIndex] > b[dataIndex] ? 1 : -1);
}
if (typeof sorter === 'function') {
result = [...result].sort(sorter);
if (sortOrder === 'descend') {
result = result.reverse();
}
}
return result;
};
const fetchData = (pagination: PageState, currentPage = 1, sorter: ColumnProps = {}, filters: ColumnProps[] = []) => {
const nextPagination = { ...pagination, currentPage };
return new Promise<FetchResult>((resolve) => {
setTimeout(() => {
let data = sortData(sorter, allData);
data = filterData(filters, data);
const dataSource = data.slice((currentPage - 1) * nextPagination.pageSize, currentPage * nextPagination.pageSize);
nextPagination.total = data.length;
resolve({
dataSource,
pagination: nextPagination,
sorter,
filters,
});
}, 1500);
});
};
const getSorterColumn = (columns: ColumnProps[]) => columns.filter((column) => !!column.sorter)[0];
const getFilterColumns = (columns: ColumnProps[]) => columns.filter((column) => Array.isArray(column.filteredValue) && column.filteredValue.length);
const loading = ref(true);
const columns = shallowRef(initialColumns);
const scroll = shallowRef<TableScroll>({});
const rowSelection = shallowRef<RowSelectionProps>();
const expandable = ref(false);
const expandCellFixed = ref(false);
const showTitle = ref(false);
const showFooter = ref(false);
const expandedRowKeys = ref<(string | number)[]>([]);
const showHeader = ref(true);
const bordered = ref(false);
const resizable = ref(false);
const pagination = shallowRef<PageState | false>(defaultPagination);
const dataSource = shallowRef<Row[]>([]);
const load = (currentPagination: PageState, currentPage?: number, sorter?: ColumnProps, filters?: ColumnProps[]) => {
fetchData(currentPagination, currentPage, sorter, filters)
.then((result) => {
let nextColumns = mergeColumns(result.sorter, columns.value);
for (const filterObj of result.filters) {
nextColumns = mergeColumns(filterObj, nextColumns);
}
columns.value = nextColumns;
loading.value = false;
pagination.value = result.pagination;
dataSource.value = result.dataSource;
})
.catch((err) => {
console.error(err);
loading.value = false;
});
};
const setPage = (page?: number | null, sorter?: ColumnProps | null, filters?: ColumnProps[]) => {
if (loading.value) {
return;
}
const currentPage = typeof page === 'number' ? page : (pagination.value && pagination.value.currentPage) || 1;
loading.value = true;
load(pagination.value || defaultPagination, currentPage, sorter || getSorterColumn(columns.value), filters || getFilterColumns(columns.value));
};
onMounted(() => {
load(defaultPagination, 1, getSorterColumn(initialColumns), []);
});
const tablePagination = computed(() => pagination.value && { ...pagination.value, onPageChange: setPage });
const toggleFixHeader = (checked: boolean) => {
scroll.value = { ...scroll.value, y: checked ? 300 : undefined };
};
const toggleFixColumns = (checked: boolean) => {
const lastIndex = columns.value.length - 1;
if (checked) {
columns.value = columns.value.map((column, index) => {
if (index === 0) {
return { ...column, fixed: true };
}
return index === lastIndex ? { ...column, fixed: 'right' } : column;
});
} else {
columns.value = columns.value.map((column) => ({ ...column, fixed: false }));
}
if (rowSelection.value) {
rowSelection.value = { ...rowSelection.value, fixed: checked };
}
scroll.value = { ...scroll.value, x: checked ? '150%' : undefined };
expandCellFixed.value = checked;
};
const toggleRowSelection = (checked: boolean) => {
rowSelection.value = checked
? {
width: 48,
fixed: true,
onChange: (selectedRowKeys, selectedRows) => console.log('Selection changed, selectedRowKeys: ', selectedRowKeys, 'selectedRows: ', selectedRows),
}
: undefined;
};
const toggleShowSorter = (checked: boolean) => {
columns.value = columns.value.map((column) => ({
...column,
sorter: checked ? initialColumns.find((item) => item.dataIndex === column.dataIndex)?.sorter : undefined,
}));
};
const toggleShowFilter = (checked: boolean) => {
if (checked) {
columns.value = columns.value.map((column) =>
column.dataIndex === 'name'
? {
...column,
filters: [
{
text: '姓名中包含 1',
value: '1',
},
{
text: '姓名中包含 2',
value: '2',
},
{
text: '姓名中包含 3',
value: '3',
},
],
filteredValue: [],
}
: column
);
} else {
columns.value = columns.value.map((column) => ({ ...column, filters: undefined, filteredValue: undefined }));
setPage(null, null, []);
}
};
const onChange = (data: TableChangeInfo) => {
console.log('Table changed: ', data);
const { pagination: pageInfo, sorter, filters } = data;
setPage(pageInfo?.currentPage, sorter, filters);
};
const toggleExpandedRowKeys = (checked: boolean) => {
if (checked) {
expandedRowKeys.value = dataSource.value.filter((data) => data.key).map((data) => data.key);
expandable.value = true;
} else {
expandedRowKeys.value = [];
}
};
const toggleResizable = (checked: boolean) => {
resizable.value = checked;
bordered.value = checked;
};
const toggleDataSource = (checked: boolean) => {
if (checked) {
dataSource.value = [];
} else {
setPage();
}
};
const switchPagination = (position: TablePaginationPosition | false) => {
pagination.value = position ? { ...defaultPagination, ...pagination.value, position } : false;
};
const switches: SwitchItem[] = [
{ text: '固定表头:', checked: () => !!scroll.value.y, onChange: toggleFixHeader },
{
text: '隐藏表头:',
onChange: (checked) => {
showHeader.value = !checked;
},
},
{
text: '显示标题:',
onChange: (checked) => {
showTitle.value = checked;
},
},
{
text: '显示底部:',
onChange: (checked) => {
showFooter.value = checked;
},
},
{ text: '固定列:', onChange: toggleFixColumns },
{ text: '显示选择列:', onChange: toggleRowSelection },
{
text: '显示加载状态:',
checked: () => loading.value,
onChange: (checked) => {
loading.value = checked;
},
},
{ text: '无数据:', checked: () => !dataSource.value.length, onChange: toggleDataSource },
{
text: '开启排序功能:',
checked: () => columns.value.some((column) => column.sorter),
onChange: toggleShowSorter,
},
{
text: '开启过滤功能:',
checked: () => columns.value.some((column) => column.filters),
onChange: toggleShowFilter,
},
{
text: '开启行展开功能:',
checked: () => expandable.value,
onChange: (checked) => {
expandable.value = checked;
},
},
{ text: '展开当前所有行:', onChange: toggleExpandedRowKeys },
{
text: '显示边框:',
checked: () => bordered.value,
onChange: (checked) => {
bordered.value = checked;
},
},
{ text: '开启列伸缩功能:', onChange: toggleResizable },
];
</script>
<template>
<div>
<div :style="wrapStyle">
<span v-for="item in switches" :key="item.text" :style="switchStyle">
<span>{{ item.text }}</span>
<Switch :aria-label="item.text" :modelValue="item.checked?.()" size="small" @change="item.onChange" />
</span>
<span :style="switchStyle">
<span>分页控件:</span>
<ButtonGroup>
<Button @click="switchPagination('bottom')">Bottom</Button>
<Button @click="switchPagination('top')">Top</Button>
<Button @click="switchPagination('both')">Both</Button>
<Button @click="switchPagination(false)">None</Button>
</ButtonGroup>
</span>
</div>
<Table
v-model:expandedRowKeys="expandedRowKeys"
:bordered="bordered"
:columns="columns"
:dataSource="dataSource"
:expandCellFixed="expandCellFixed"
:loading="loading"
:pagination="tablePagination"
:resizable="resizable"
:rowSelection="rowSelection"
:scroll="scroll"
:showHeader="showHeader"
:title="showTitle ? 'This is title.' : undefined"
@change="onChange"
>
<template #cell="{ column, record, text }">
<span v-if="column.dataIndex === 'name'">
<Avatar alt="" shape="square" size="small" :src="figmaIconUrl" :style="{ marginRight: '12px' }" />
{{ text }}
</span>
<template v-else-if="column.dataIndex === 'size'">{{ text }} KB</template>
<div v-else-if="column.dataIndex === 'owner'">
<Avatar :color="record.avatarBg" size="small" :style="{ marginRight: '4px' }">
{{ typeof text === 'string' && text.slice(0, 1) }}
</Avatar>
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'updateTime'">
{{ dateFns.format(new Date(text), 'yyyy-MM-dd') }}
</template>
</template>
<template v-if="expandable" #expandedRow="{ record }">
<p>{{ record.description }}</p>
</template>
<template v-if="showFooter" #footer>
<p :style="{ margin: 0 }">This is footer.</p>
</template>
</Table>
</div>
</template>Fully custom rendering
Generally, the #cell slot is enough, but you can also pass Column.useFullRender = true to enable full custom rendering mode. At this time the output of the slot replaces the whole cell, and the checkbox, expand button and indent nodes are passed to the #headerCell slot (or #title of Table.Column) and the #cell slot, so you can further define the rendering of the header and cell content.
The parameter of #headerCell is:
{
column: ColumnProps,
title: string | undefined, // column title
filter: VNode | null, // Filter button
sorter: VNode | null, // Sort button
selection: VNode | null, // Select button
}
The parts of the #cell parameter that relate to full custom rendering are:
{
expandIcon: VNode | null, // Expand button
selection: VNode | null, // Select button
indentText: VNode | null, // Indentation
}
Render these nodes with <component :is="selection" />.
The example below renders the checkbox and content into the same cell and header.
| Name | 所有者 | ||
|---|---|---|---|
| 0 KB | 姜 姜鹏志 | 2024-05-06 | |
| 5 KB | 郝 郝宣 | 2024-05-11 | |
| 10 KB | 姜 姜鹏志 | 2024-05-16 | |
| 15 KB | 郝 郝宣 | 2024-05-21 | |
| 20 KB | 姜 姜鹏志 | 2024-05-26 | |
| 25 KB | 郝 郝宣 | 2024-05-31 | |
| 30 KB | 姜 姜鹏志 | 2024-06-05 | |
| 35 KB | 郝 郝宣 | 2024-06-10 | |
| 40 KB | 姜 姜鹏志 | 2024-06-15 | |
| 45 KB | 郝 郝宣 | 2024-06-20 | |
| 50 KB | 姜 姜鹏志 | 2024-06-25 | |
| 55 KB | 郝 郝宣 | 2024-06-30 |
Code
<script setup lang="ts">
import * as dateFns from 'date-fns';
import { Avatar, Table, type ColumnProps, type RowSelectionProps } from '@fibrous/semi-ui-vue';
const DAY = 24 * 60 * 60 * 1000;
const figmaIconUrl = '/assets/placeholder/app.svg';
interface Row {
key: string;
name: string;
owner: string;
size: number;
updateTime: number;
avatarBg: 'grey' | 'red';
}
const columns: ColumnProps<Row>[] = [
{
title: 'Name',
dataIndex: 'name',
width: 400,
filters: [
{
text: 'Semi Design 设计稿',
value: 'Semi Design 设计稿',
},
{
text: 'Semi D2C 设计稿',
value: 'Semi D2C 设计稿',
},
],
onFilter: (value, record) => record.name.includes(value),
useFullRender: true,
},
{
title: '大小',
dataIndex: 'size',
sorter: (a, b) => (a.size - b.size > 0 ? 1 : -1),
},
{
title: '所有者',
dataIndex: 'owner',
},
{
title: '更新日期',
dataIndex: 'updateTime',
sorter: (a, b) => (a.updateTime - b.updateTime > 0 ? 1 : -1),
},
];
const getData = (total: number) => {
const data: Row[] = [];
for (let i = 0; i < total; i++) {
const isSemiDesign = i % 2 === 0;
const randomNumber = (i * 1000) % 199;
data.push({
key: '' + i,
name: isSemiDesign ? `Semi Design 设计稿${i}.fig` : `Semi D2C 设计稿${i}.fig`,
owner: isSemiDesign ? '姜鹏志' : '郝宣',
size: randomNumber,
updateTime: new Date(2024, 4, 6, 12).valueOf() + randomNumber * DAY,
avatarBg: isSemiDesign ? 'grey' : 'red',
});
}
return data;
};
const dataSource = getData(46);
const pagination = { pageSize: 12 };
const rowSelection: RowSelectionProps<Row> = {
hidden: true,
fixed: 'left',
};
const onChange = (changeInfo: unknown) => console.log(changeInfo);
</script>
<template>
<Table :columns="columns" :dataSource="dataSource" :pagination="pagination" :rowSelection="rowSelection" @change="onChange">
<template #headerCell="{ column, title, sorter, filter, selection }">
<span v-if="column.dataIndex === 'name'" :style="{ display: 'inline-flex', alignItems: 'center', paddingLeft: '20px' }">
<component :is="selection" />
<span :style="{ marginLeft: '8px' }">{{ title }}</span>
<component :is="sorter" />
<component :is="filter" />
</span>
</template>
<template #cell="{ column, text, record, expandIcon, selection, indentText }">
<span v-if="column.dataIndex === 'name'" :style="{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }">
<component :is="indentText" />
<component :is="expandIcon" />
<component :is="selection" />
<span :style="{ marginLeft: '8px' }">
<Avatar alt="" shape="square" size="small" :src="figmaIconUrl" :style="{ marginRight: '12px' }" />
{{ text }}
</span>
</span>
<template v-else-if="column.dataIndex === 'size'">{{ text }} KB</template>
<div v-else-if="column.dataIndex === 'owner'">
<Avatar :color="record.avatarBg" size="small" :style="{ marginRight: '4px' }">
{{ typeof text === 'string' && text.slice(0, 1) }}
</Avatar>
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'updateTime'">
{{ dateFns.format(new Date(text), 'yyyy-MM-dd') }}
</template>
</template>
<template #expandedRow="{ record }">
<article>{{ record.name }}</article>
</template>
</Table>
</template>Header Merge
Users can use the header merge function to group the header. The header merge can be combined with fixed column, virtualization, data grouping, column scaling and other functions. It also supports Table.Column or configurable writing.
Combined Header Configuration Writing
| 基本信息 | 其他信息 | 更多 | |||
|---|---|---|---|---|---|
标题 | 所有者 | ||||
| 0 KB | 姜 姜鹏志 | 2024-05-06 | |||
| 5 KB | 郝 郝宣 | 2024-05-11 | |||
| 10 KB | 姜 姜鹏志 | 2024-05-16 | |||
| 15 KB | 郝 郝宣 | 2024-05-21 | |||
| 20 KB | 姜 姜鹏志 | 2024-05-26 | |||
| 25 KB | 郝 郝宣 | 2024-05-31 | |||
| 30 KB | 姜 姜鹏志 | 2024-06-05 | |||
| 35 KB | 郝 郝宣 | 2024-06-10 | |||
| 40 KB | 姜 姜鹏志 | 2024-06-15 | |||
| 45 KB | 郝 郝宣 | 2024-06-20 |
Code
<script setup lang="ts">
import * as dateFns from 'date-fns';
import { IconMore } from '@fibrous/semi-icons-vue';
import { Avatar, Table, type ColumnProps } from '@fibrous/semi-ui-vue';
const DAY = 24 * 60 * 60 * 1000;
const figmaIconUrl = '/assets/placeholder/app.svg';
interface Row {
key: string;
name: string;
owner: string;
size: number;
updateTime: number;
avatarBg: 'grey' | 'red';
}
const columns: ColumnProps<Row>[] = [
{
title: '基本信息',
fixed: 'left',
children: [
{
title: '标题',
dataIndex: 'name',
width: 300,
fixed: true,
filters: [
{
text: 'Semi Design 设计稿',
value: 'Semi Design 设计稿',
},
{
text: 'Semi D2C 设计稿',
value: 'Semi D2C 设计稿',
},
],
onFilter: (value, record) => record.name.includes(value),
},
{
title: '大小',
dataIndex: 'size',
width: 100,
fixed: true,
sorter: (a, b) => (a.size - b.size > 0 ? 1 : -1),
},
],
},
{
title: '其他信息',
children: [
{
title: '所有者',
dataIndex: 'owner',
},
{
title: '更新日期',
dataIndex: 'updateTime',
sorter: (a, b) => (a.updateTime - b.updateTime > 0 ? 1 : -1),
},
],
},
{
title: '更多',
fixed: 'right',
width: 100,
align: 'center',
dataIndex: 'operate',
},
];
const getData = (total: number) => {
const data: Row[] = [];
for (let i = 0; i < total; i++) {
const isSemiDesign = i % 2 === 0;
const randomNumber = (i * 1000) % 199;
data.push({
key: '' + i,
name: isSemiDesign ? `Semi Design 设计稿${i}.fig` : `Semi D2C 设计稿${i}.fig`,
owner: isSemiDesign ? '姜鹏志' : '郝宣',
size: randomNumber,
updateTime: new Date(2024, 4, 6, 12).valueOf() + randomNumber * DAY,
avatarBg: isSemiDesign ? 'grey' : 'red',
});
}
return data;
};
const data = getData(46);
const rowSelection = { fixed: true };
const scroll = { x: 1000, y: 400 };
const onChange = (changeInfo: unknown) => console.log(changeInfo);
</script>
<template>
<Table :columns="columns" :dataSource="data" :rowSelection="rowSelection" :scroll="scroll" @change="onChange">
<template #cell="{ column, text, record }">
<span v-if="column.dataIndex === 'name'">
<Avatar alt="" shape="square" size="small" :src="figmaIconUrl" :style="{ marginRight: '12px' }" />
{{ text }}
</span>
<template v-else-if="column.dataIndex === 'size'">{{ text }} KB</template>
<div v-else-if="column.dataIndex === 'owner'">
<Avatar :color="record.avatarBg" size="small" :style="{ marginRight: '4px' }">
{{ typeof text === 'string' && text.slice(0, 1) }}
</Avatar>
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'updateTime'">
{{ dateFns.format(new Date(text), 'yyyy-MM-dd') }}
</template>
<IconMore v-else-if="column.dataIndex === 'operate'" />
</template>
<template #expandedRow="{ record }">
<article>{{ record.name }}</article>
</template>
</Table>
</template>Merge Header Table.Column Writing
| 基本信息 | 其他信息 | 更多 | |||
|---|---|---|---|---|---|
标题 | 所有者 | ||||
| 0 KB | 姜 姜鹏志 | 2024-05-06 | |||
| 5 KB | 郝 郝宣 | 2024-05-11 | |||
| 10 KB | 姜 姜鹏志 | 2024-05-16 | |||
| 15 KB | 郝 郝宣 | 2024-05-21 | |||
| 20 KB | 姜 姜鹏志 | 2024-05-26 | |||
| 25 KB | 郝 郝宣 | 2024-05-31 | |||
| 30 KB | 姜 姜鹏志 | 2024-06-05 | |||
| 35 KB | 郝 郝宣 | 2024-06-10 | |||
| 40 KB | 姜 姜鹏志 | 2024-06-15 | |||
| 45 KB | 郝 郝宣 | 2024-06-20 |
Code
<script setup lang="ts">
import * as dateFns from 'date-fns';
import { IconMore } from '@fibrous/semi-icons-vue';
import { Avatar, Table, TableColumn as Column } from '@fibrous/semi-ui-vue';
const DAY = 24 * 60 * 60 * 1000;
const figmaIconUrl = '/assets/placeholder/app.svg';
interface Row {
key: string;
name: string;
owner: string;
size: number;
updateTime: number;
avatarBg: 'grey' | 'red';
}
const getData = (total: number) => {
const data: Row[] = [];
for (let i = 0; i < total; i++) {
const isSemiDesign = i % 2 === 0;
const randomNumber = (i * 1000) % 199;
data.push({
key: '' + i,
name: isSemiDesign ? `Semi Design 设计稿${i}.fig` : `Semi D2C 设计稿${i}.fig`,
owner: isSemiDesign ? '姜鹏志' : '郝宣',
size: randomNumber,
updateTime: new Date(2024, 4, 6, 12).valueOf() + randomNumber * DAY,
avatarBg: isSemiDesign ? 'grey' : 'red',
});
}
return data;
};
const data = getData(46);
const rowSelection = { fixed: true };
const scroll = { x: 1000, y: 400 };
const nameFilters = [
{
text: 'Semi Design 设计稿',
value: 'Semi Design 设计稿',
},
{
text: 'Semi D2C 设计稿',
value: 'Semi D2C 设计稿',
},
];
const filterName = (value: string, record: Row) => record.name.includes(value);
const sortSize = (a: Row, b: Row) => (a.size - b.size > 0 ? 1 : -1);
const sortUpdateTime = (a: Row, b: Row) => (a.updateTime - b.updateTime > 0 ? 1 : -1);
const onChange = (changeInfo: unknown) => console.log(changeInfo);
</script>
<template>
<Table :dataSource="data" :rowSelection="rowSelection" :scroll="scroll" @change="onChange">
<Column fixed="left" title="基本信息">
<Column dataIndex="name" :filters="nameFilters" fixed :onFilter="filterName" title="标题" :width="300">
<template #cell="{ text }">
<span>
<Avatar alt="" shape="square" size="small" :src="figmaIconUrl" :style="{ marginRight: '12px' }" />
{{ text }}
</span>
</template>
</Column>
<Column dataIndex="size" fixed :sorter="sortSize" title="大小" :width="100">
<template #cell="{ text }">{{ text }} KB</template>
</Column>
</Column>
<Column title="其他信息">
<Column dataIndex="owner" title="所有者">
<template #cell="{ text, record }">
<div>
<Avatar :color="record.avatarBg" size="small" :style="{ marginRight: '4px' }">
{{ typeof text === 'string' && text.slice(0, 1) }}
</Avatar>
{{ text }}
</div>
</template>
</Column>
<Column dataIndex="updateTime" :sorter="sortUpdateTime" title="更新日期">
<template #cell="{ text }">{{ dateFns.format(new Date(text), 'yyyy-MM-dd') }}</template>
</Column>
</Column>
<Column align="center" dataIndex="operate" fixed="right" title="更多" :width="100">
<template #cell>
<IconMore />
</template>
</Column>
<template #expandedRow="{ record }">
<article>{{ record.name }}</article>
</template>
</Table>
</template>colSpan and rowSpan
- In addition to merging the headers by writing children, you can merge the headers by setting column.colSpan.
- Table supports row/column merging.
column.onCellreturns the cell attributescolSpanorrowSpan; when set to 0, the cell will not be rendered.
type OnCell = (record: RecordType, rowIndex: number) => TableCellAttrs;
// TableCellAttrs: the attributes and listeners a td supports, plus colSpan and rowSpan
| 标题 | 大小 | 所有者 | |
|---|---|---|---|
| 5 KB | 郝 郝宣 | 2024-05-11 | |
姜 姜鹏志 | |||
| 15 KB | 郝 郝宣 | 2024-05-21 | |
| 20 KB | 姜 姜鹏志 | 2024-05-26 | |
Code
<script setup lang="ts">
import * as dateFns from 'date-fns';
import { Avatar, Table, type ColumnProps } from '@fibrous/semi-ui-vue';
const figmaIconUrl = '/assets/placeholder/app.svg';
const DAY = 24 * 60 * 60 * 1000;
interface Row {
key: string;
name: string;
owner: string;
size: number;
updateTime: number;
avatarBg: 'grey' | 'red';
}
const columns: ColumnProps<Row>[] = [
{
title: '标题',
dataIndex: 'name',
width: 400,
onCell: (_record, index) => {
if (index === 0) {
return { colSpan: 4 };
}
if (index === 1) {
return { rowSpan: 2 };
}
if (index === 2) {
return { rowSpan: 0 };
}
return {};
},
},
{
title: '大小',
dataIndex: 'size',
onCell: (_record, index) => {
if (index === 0) {
return { colSpan: 0 };
}
if (index === 1) {
return { rowSpan: 2 };
}
if (index === 2) {
return { rowSpan: 0 };
}
return {};
},
},
{
title: '所有者',
dataIndex: 'owner',
onCell: (_record, index) => (index === 0 ? { colSpan: 0 } : {}),
},
{
title: '更新日期',
dataIndex: 'updateTime',
sorter: (a, b) => (a.updateTime - b.updateTime > 0 ? 1 : -1),
onCell: (_record, index) => {
if (index === 0) {
return { colSpan: 0 };
}
if (index === 1) {
return { rowSpan: 2 };
}
if (index === 2) {
return { rowSpan: 0 };
}
return {};
},
},
];
const dataSource: Row[] = [];
for (let i = 0; i < 5; i++) {
const isSemiDesign = i % 2 === 0;
const randomNumber = (i * 1000) % 199;
dataSource.push({
key: '' + i,
name: isSemiDesign ? `Semi Design 设计稿${i}.fig` : `Semi D2C 设计稿${i}.fig`,
owner: isSemiDesign ? '姜鹏志' : '郝宣',
size: randomNumber,
updateTime: new Date(2024, 4, 6, 12).valueOf() + randomNumber * DAY,
avatarBg: isSemiDesign ? 'grey' : 'red',
});
}
</script>
<template>
<Table :columns="columns" :dataSource="dataSource" :pagination="false">
<template #cell="{ column, record, text }">
<div v-if="column.dataIndex === 'name'">
<Avatar alt="" shape="square" size="small" :src="figmaIconUrl" :style="{ marginRight: '12px' }" />
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'size'">{{ text }} KB</template>
<div v-else-if="column.dataIndex === 'owner'">
<Avatar :color="record.avatarBg" size="small" :style="{ marginRight: '4px' }">
{{ typeof text === 'string' && text.slice(0, 1) }}
</Avatar>
{{ text }}
</div>
<template v-else-if="column.dataIndex === 'updateTime'">
{{ dateFns.format(new Date(text), 'yyyy-MM-dd') }}
</template>
</template>
</Table>
</template>API Reference
Table
Props
| Property | Description | Type | Default |
|---|---|---|---|
| bordered | Whether to show the outer border and the column borders. | boolean | undefined |
| childrenRecordName | The field of a record that holds its child records in a tree table. | string | undefined |
| clickGroupedRowToExpand | Clicking a group row expands or collapses the group. | boolean | undefined |
| columns | The column configuration, see Column. When given, an empty array included, it takes precedence over the Table.Column children. | TypeColumnProps<R>[] | undefined |
| components | Replaces the elements Table renders, such as table, body, row, td and th, with a tag name or a Vue component that receives the attributes and listeners of the element it replaces. | TableComponents | undefined |
| dataSource | The data. Give every record a unique key, or name the primary key field with rowKey. Rows added or removed in place (push, splice) are sorted and filtered again; a record field changed in place shows in its cell but does not sort or filter again. | R[] | undefined |
| defaultExpandAllGroupRows | Whether all group rows start expanded. Has no effect on data loaded later. | boolean | undefined |
| defaultExpandAllRows | Whether all rows start expanded. Has no effect on data loaded later. | boolean | undefined |
| defaultExpandedRowKeys | The keys of the rows that start expanded. Has no effect on data loaded later. | (string | number)[] | undefined |
| direction | The text direction. Defaults to the direction of ConfigProvider and can be set here per table. | "ltr" | "rtl" | semiGlobalDefault("Table", "direction") |
| expandAllGroupRows | Whether all group rows are expanded. | boolean | undefined |
| expandAllRows | Whether all rows are expanded. | boolean | undefined |
| expandCellFixed | Whether the column of the expand button is fixed, with the same values as the fixed field of a column. | boolean | "left" | "right" | undefined |
| expandIcon | Accepts only false, which hides the expand buttons. Use the expandIcon slot for a custom icon. | boolean | undefined |
| expandedRowKeys | The keys of the expanded rows. When given, row expansion is controlled; use it with v-model:expandedRowKeys. | (string | number)[] | undefined |
| expandRowByClick | Whether clicking a row expands an expandable row. | boolean | undefined |
| footer | The table footer as plain text. The footer slot takes precedence. | string | undefined |
| groupBy | The grouping rule: a record field name, or a function that returns a string or a number. | TypeTableGroupBy<R> | undefined |
| groupSectionColumn | The column configuration of the single cell of a group row. The returned object has no title, children or dataIndex. | Type((groupKey: string | number, group: (string | number)[]) => Omit<ColumnProps<R>, "title" | "children" | "dataIndex">) | undefined |
| headerStyle | Inline style of every header cell, fixed headers included. | CSSProperties | undefined |
| hideExpandedColumn | In an expandable table the expand button shares the first cell by default; set false to render it as its own column. | boolean | undefined |
| indentSize | The indent of each tree level, in pixels. | number | undefined |
| keepDOM | Whether collapsing a row keeps its DOM. | boolean | undefined |
| loading | Whether the table shows its loading state. | boolean | undefined |
| pagination | The pagination configuration. Pass false to turn pagination off. | boolean | TablePaginationProps | undefined |
| prefixCls | The prefix of the class names. | string | undefined |
| resizable | Whether columns can be resized; a resizable column needs a width. An object configures onResize, onResizeStart, onResizeStop and handlerClassName. | Typeboolean | ResizableProps<R> | undefined |
| rowExpandable | Tells whether a row can be expanded. A row that returns false has no expand button. | TypeTableRowExpandable<R> | undefined |
| rowKey | The row key: a record field name, or a function that returns a string or a number. | TypeTableRowKey<R> | undefined |
| rowSelection | The row selection configuration. Pass true for the defaults, see rowSelection. | Typeboolean | RowSelectionProps<R> | undefined |
| rowSpanHover | Hovering a cell with rowSpan highlights every row the cell spans. | boolean | undefined |
| scroll | The scroll area: x is the width and y the height, see scroll. | TableScroll | undefined |
| showHeader | Whether to show the header. | boolean | undefined |
| size | The table size, which sets the padding of the cells. | "small" | "default" | "middle" | undefined |
| sticky | Sticks the header to the top of the page. With an object, top is the distance from the scroll container. | TableSticky | undefined |
| title | The table title as plain text. The title slot takes precedence. | string | undefined |
| virtualized | Turns on virtualization, which needs scroll.y as a number. An object sets the row height itemSize and the extra rows overscanCount. | TableVirtualized | undefined |
| onGroupedRow | Like onRow, for group rows. The returned object holds the attributes and listeners of the tr. index is the group's ordinal, or its position among the virtual list's rows when virtualized is on. | Type((record: { groupKey: string | number; records: R[]; }, index: number) => TableRowAttrs) | undefined |
| onHeaderRow | Sets the attributes and listeners of a header row. The returned object (without style) is merged into the row. | Type((columns: ColumnProps<R>[], index: number) => Omit<TableRowAttrs, "style">) | undefined |
| onRow | Sets the attributes and listeners of a data row; the third argument is the row state. The returned listeners run after the row's own handling and the rowXxx events. | Type((record: R, index: number, rowState: { disabled: boolean; selected: boolean; }) => TableRowAttrs) | undefined |
Events
| Event | Description | Callback parameters |
|---|---|---|
| scroll | Emitted when the vertical offset of a virtualized body changes. A horizontal scroll does not emit it. | [args: VirtualListScrollArgs] |
| change | Emitted when the page, the sorting or the filters change. The argument holds pagination, filters, sorter and extra.changeType. | Type[changeInfo: TableChangeInfo<R>] |
| expand | Emitted when an expand button is clicked, with the expanded state, the record (an object with groupKey for a group row) and the mouse event. | Type[expanded: boolean, record: TableIncludeGroupRecord<R>, event: MouseEvent] |
| expandedRowsChange | Emitted when the expanded rows change, with the array of expanded records. | Type[expandedRows: TableIncludeGroupRecord<R>[]] |
| update:expandedRowKeys | Emitted when the expanded rows change, with the array of expanded keys, group keys included. Backs v-model:expandedRowKeys. | [expandedRowKeys: (string | number)[]] |
| rowMouseEnter | Emitted when the pointer enters a data row, before the onMouseenter returned by onRow. | [record: R, event: MouseEvent] |
| rowMouseLeave | Emitted when the pointer leaves a data row, before the onMouseleave returned by onRow. | [record: R, event: MouseEvent] |
| rowDoubleClick | Emitted when a data row is double-clicked, before the onDblclick returned by onRow. | [record: R, event: MouseEvent] |
| rowContextMenu | Emitted when a data row opens the context menu, before the onContextmenu returned by onRow. | [record: R, event: MouseEvent] |
Slots
| Slot | Description | Scope parameters |
|---|---|---|
| default | Table.Column children. Ignored when columns is given. | any |
| cell | The content of a data cell, called for every data column; tell the columns apart with column.dataIndex or column.key. Empty output shows the value. The cell slot of a Table.Column takes precedence. | TypeTableCellSlotProps<R> |
| headerCell | The content of a column title. Empty output shows column.title. The title slot of a Table.Column takes precedence. | TypeTableHeaderCellSlotProps<R> |
| title | The table title, with the records of the current page as pageData. | TypeTableTitleSlotProps<R> |
| footer | The table footer, with the records of the current page as pageData. | TypeTableTitleSlotProps<R> |
| empty | The content shown without data. Without the slot the locale's empty text shows; an empty slot shows nothing. | any |
| expandedRow | The content of an expanded row, with record, index and expanded. Empty output leaves the row out. | TypeTableExpandedRowSlotProps<R> |
| groupSection | The content of a group row, with groupKey and group (the row keys of the group). | TableGroupSectionSlotProps |
| sortIcon | The sort icon, with sortOrder and column. Empty output shows the default arrows. The sortIcon slot of a Table.Column takes precedence. | TypeTableSortIconSlotProps<R> |
| filterIcon | The content of the filter button, with filtered and column. Empty output shows the default icon. The filterIcon slot of a Table.Column takes precedence. | TypeTableFilterIconSlotProps<R> |
| filterDropdown | The filter panel of a column with filterDropdown set to true, with the temporary value and onConfirm, onClear, onClose, onReset. Empty output shows the filter menu. | TypeTableFilterDropdownSlotProps<R> |
| filterDropdownItem | An item of the filter menu, with text, value, checked, level, onChange and more. Empty output shows the default item. | TypeTableFilterDropdownItemSlotProps<R> |
| selectionCell | A cell of the selection column, called for the header and the rows, with selected, inHeader, originNode and more. Empty output shows the default checkbox. | TypeTableSelectionCellSlotProps<R> |
| expandIcon | The icon of an expand button, with expanded. Empty output shows the default icon. A custom icon does not rotate. | TableExpandIconSlotProps |
| pagination | Replaces the pagination info and the Pagination. The pagination argument can be bound to a Pagination as is. Empty output shows the default pagination. | TablePaginationSlotProps |
Exposes
| Name | Description | Type |
|---|---|---|
| None |
Native attributes such as class, style, id and data-* land on the outermost element through attrs; aria-label, aria-labelledby and aria-describedby land on the element with role="table" (the shared container of the header and the body when they are separated or virtualized, otherwise the table of the body). When the table has a title and the caller passes no name, the table points to the title through aria-labelledby.
TableProps, TableEmits, TableSlots, TableHandle and the data types can all be imported from @fibrous/semi-ui-vue. RecordType is their generic parameter R, Record<string, any> by default.
The fields of virtualized when it is an object (TableVirtualizedProps):
| Field | Instructions | Type | Default |
|---|---|---|---|
| itemSize | Row height. When not passed, the default follows size: 53 for default, 45 for middle and 37 for small, and a group header row is as high as a normal row | number | ((index: number, row: { sectionRow?: boolean, expandedRow?: boolean }) => number) | 53 |
| overscanCount | Rows rendered above and below the visible area | number | 2 |
The values of components are tag names or Vue components. A component receives the attributes and listeners of the replaced element, and its default slot is the content of the element. The positions that can be replaced (TableComponents):
| Position | Instructions |
|---|---|
| header.outer, header.wrapper, header.row, header.cell | table, thead, tr and th of the header |
| body.outer, body.wrapper, body.row, body.cell | table, tbody, tr and td of the body |
| body.colgroup.wrapper, body.colgroup.col | colgroup and col |
headerStyle Example
headerStyle will be applied to all header <th> elements, including fixed columns.
<script setup lang="ts">
import { Table } from '@fibrous/semi-ui-vue';
import type { ColumnProps } from '@fibrous/semi-ui-vue';
const columns: ColumnProps[] = [
{ title: 'Name', dataIndex: 'name', width: 180, fixed: 'left' },
{ title: 'Age', dataIndex: 'age', width: 120 },
{ title: 'Address', dataIndex: 'address', width: 280 },
{ title: 'Company', dataIndex: 'company', width: 280 },
];
const dataSource = Array.from({ length: 6 }).map((_, i) => ({
key: i,
name: `Edward ${i}`,
age: 20 + i,
address: 'No. 1, Lake Park',
company: 'Semi Design',
}));
</script>
<template>
<Table :columns="columns" :dataSource="dataSource" :scroll="{ x: 900 }" :headerStyle="{ backgroundColor: '#F5F6F7', fontWeight: 600 }" />
</template>
Some of the type definitions used above, all importable from @fibrous/semi-ui-vue:
// PaginationProps is the props supported by the Pagination component
interface TablePaginationProps extends PaginationProps {
position?: 'top' | 'bottom' | 'both';
formatPageText?: boolean | ((pageInfo: { currentStart: number; currentEnd: number; total: number }) => string);
onChange?: (currentPage: number, pageSize: number) => void;
onPageChange?: (currentPage: number) => void;
onPageSizeChange?: (pageSize: number) => void;
}
RecordType is the generic parameter R of Table and Column, Record<string, any> by default. You can use it like this:
<script setup lang="ts">
import { Table } from '@fibrous/semi-ui-vue';
import type { ColumnProps } from '@fibrous/semi-ui-vue';
interface Row {
key: string;
name: string;
age: number;
address: string;
}
const columns: ColumnProps<Row>[] = [
{ title: 'Name', dataIndex: 'name', width: 200 },
// ...
];
const data: Row[] = [
{ key: '1', name: 'John Brown', age: 32, address: 'New York No. 1 Lake Park' },
// ...
];
</script>
<template>
<Table :columns="columns" :dataSource="data" />
</template>
onRow/onHeaderRow Usage
Also in
column.onCellcolumn.onHeaderCellProperties or events supported by td / th can also be returned.
The third parameter rowStatus of onRow can get the current row's status information, including disabled and selected properties. This is useful when you need to execute different logic based on the row's selected or disabled state, for example, determining whether to allow selection when clicking a row.
The listeners in the returned object use Vue's onXxx naming (onClick, onMouseenter, onMouseleave), and the style class is class.
<script setup lang="ts">
import { Table } from '@fibrous/semi-ui-vue';
const onRow = (record, index, rowStatus) => ({
onClick: () => {
// rowStatus.disabled indicates whether the current row is disabled
// rowStatus.selected indicates whether the current row is selected
if (rowStatus.disabled) {
return;
}
console.log('Clicked row', index, rowStatus);
},
onMouseenter: () => {},
onMouseleave: () => {},
class: '',
// Other attributes or events that can be applied to tr
});
const onHeaderRow = (columns, index) => ({
onClick: () => {},
class: '',
// Other attributes or events that can be applied to tr
});
</script>
<template>
<Table :columns="columns" :dataSource="dataSource" :onRow="onRow" :onHeaderRow="onHeaderRow" />
</template>
Column
A column accepts only the properties below, and a misspelled property name is a type error. To carry custom fields on a column, extend the type with an intersection, such as ColumnProps<RecordType> & { tooltip: string }.
| Parameters | Instructions | Type | Default |
|---|---|---|---|
| align | Setting the alignment of columns, switched automatically in RTL | 'left' | 'right' | 'center' | 'left' |
| children | Settings for sub-columns when the header is merged | Column[] | |
| class | Column style name | string | object | array | |
| colSpan | When header columns merge, set to 0, do not render | number | |
| dataIndex | The key corresponding to the column data in the data item. It is required when using sorter or filter. | string | |
| defaultFilteredValue | Default value of the filter, the filter state of the external control column with a value of the screened value array | any[] | |
| defaultSortOrder | The default value of sortOrder, one of 'ascend'|'descend'|false | boolean | string | false |
| ellipsis | Ellipsis Text, table-layout will automatically switch to fixed after it is turned on | boolean | { showTitle: boolean } | false |
| filterChildrenRecord | Whether the child data needs to be filtered locally. If this function is enabled, if the child meets the filtering criteria, the parent will retain it even if it does not meet the criteria. | boolean | |
| filterDropdown | Shows the filter button when true; the content of the panel is given by the #filterDropdown slot of Table, which needs to write a variety of interactions | boolean | |
| filterDropdownProps | Props and event listeners (keys starting with on) passed to Dropdown; the trigger is always click, see more in Dropdown API | object | |
| filterDropdownVisible | Visible of Dropdown, see more in Dropdown API | boolean | |
| filterMultiple | Whether to choose more | boolean | true |
| filterConfirmMode | Filter confirm mode. immediate means filter immediately when clicking option; confirm means filter after clicking confirm button, and the dropdown panel will show confirm and reset buttons at the bottom | 'immediate' | 'confirm' | 'immediate' |
| filteredValue | Controlled property of the filter, the filter state of the external control column with a value of the screened value array | any[] | |
| filters | Filter menu items for the header | Filter[] | |
| fixed | Whether the column is fixed, optional true (equivalent to left) 'left' 'right', switched automatically in RTL | boolean | string | false |
| key | Identifies the column for selection, sorting, filtering and widths; can be omitted when a unique dataIndex is set | string | number | |
| resize | Whether to enable resize mode, this property will take effect only after Table resizable is enabled | boolean | |
| showSortTip | Whether to display sorting tips, If sortOrder is set and sorting is controlled, this parameter will not take effect | boolean | false |
| sortChildrenRecord | Whether to sort child data locally | boolean | |
| sortOrder | The controlled property of the sorting, the sorting of this control column can be set to 'ascend'|'descend'|false | boolean | string | false |
| sorter | Sorting function, local sorting uses a function (refer to the compareFunction of Array.sort), requiring a server-side sorting can be set to true. An independent dataIndex must be set for the sort column, and an independent key must be set for each data item in the dataSource | boolean | (r1: RecordType, r2: RecordType, sortOrder: 'ascend' | 'descend') => number | true |
| title | Plain text shown in the column header, also the content of the ellipsis Tooltip and the name of the sort button. Use the #headerCell slot for custom content | string | |
| useFullRender | Whether to completely customize the rendering, see Fully custom rendering for usage details, enabling this feature will cause a certain performance loss | boolean | false |
| width | Column width | string | number | |
| onCell | Set cell properties | (record: RecordType, rowIndex: number) => object | |
| onFilter | Determine the running function of the filter in local mode. An independent dataIndex must be set for the filter column, and an independent key must be set for each data item in the dataSource | (filteredValue: any, record: RecordType) => boolean | |
| onFilterDropdownVisibleChange | A callback when a custom filter menu is visible | (visible: boolean) => void | |
| onHeaderCell | Set the head cell property; index is the index of the header row | (column: Column, columnIndex: number, index: number) => object |
Customize cells, headers, sort and filter icons and filter items with the slots of Table: #cell, #headerCell, #sortIcon, #filterIcon, #filterDropdown and #filterDropdownItem; see the Slots of Table above for their parameters. With Table.Column, these slots can also be written on the column (with #title in place of #headerCell), and they take precedence over the slots of the same name on Table; a column with a #filterDropdown slot counts as having filterDropdown: true, and nested Table.Column children go in the default slot as grouped child columns. There are no render, renderFilterDropdown, renderFilterDropdownItem or shouldCellUpdate.
Some of the type definitions used above:
type Filter = {
value: any;
text: string;
children?: Filter[];
};
rowSelection
| Parameters | Instructions | Type | Default |
|---|---|---|---|
| class | Style name listed | string | object | array | |
| checkRelation | Parent-child node selection association mode. When set to 'related', selecting a parent node automatically selects all child nodes, and selecting a child node affects the parent node's state (checked/half-checked/unchecked). Default is 'unRelated', meaning parent and child node selections are independent. | 'related' | 'unRelated' | 'unRelated' |
| clickRow | Whether to enable click row to select. When enabled, clicking anywhere on the row will trigger selection/deselection, including fixed columns. Disabled rows (via getCheckboxProps) cannot be selected by clicking; when disabled is true, clicking a row does not select it either. | boolean | false |
| defaultSelectedRowKeys | The keys of the rows selected initially; read only on mount and ignored when selectedRowKeys is set | (string | number)[] | |
| disabled | Disabled Checkbox in Table header or not; when true, clickRow selection does not take effect either | boolean | false |
| fixed | Secure the selection box column to the left. | boolean | false |
| getCheckboxProps | Default property configuration for the selection box | (record: RecordType) => object | |
| hidden | Hide selection column or not | boolean | false |
| selectedRowKeys | Specifies the key array of the selected item, which needs to work with onChange | (string | number)[] | |
| width | Custom list selection box width | string | number | |
| onChange | A callback in the event of a change in the selected item. The first parameter will save the row keys selected last time, even if you do paging control or update the dataSource FAQ | (selectedRowKeys: (string | number)[], selectedRows: RecordType[]) => void | |
| onCell | Set the attributes of the data cells of the selection column | (record: RecordType, rowIndex: number) => object | |
| onHeaderCell | Set the head cell property; index is the index of the header row | (column: Column, columnIndex: number, index: number) => object | |
| onSelect | Callback when the user manually selects a row. event is the selection box's change event, or the mouse event when clickRow selects on a row click | (record: RecordType, selected: boolean, selectedRows: RecordType[], event: Event) => void | |
| onSelectAll | The user manually clicks the callback of the header selection box, and all selectable rows in the current filter result (disabled rows excluded) will be selected/unselected. changedRows contains only the rows whose selection state changed | (selected: boolean, selectedRows: RecordType[], changedRows: RecordType[], event: Event) => void |
Customize the selection box with the #selectionCell slot of Table; there are no renderCell or shouldCellUpdate.
scroll
| Parameters | Instructions | Type | Default |
|---|---|---|---|
| scrollToFirstRowOnChange | Whether to automatically scroll to the top of the table after paging, sorting, and filtering changes. When scroll.y is set, it scrolls the table body to the top; when scroll.y is not set, it scrolls the page to the table header position | boolean | false |
| x | Set the width of the horizontal scroll area, which can be pixel value, percentage, or 'max-content' | string|number | |
| y | Set the height of the vertical scroll area, which can be a pixel value | number |
pagination
Page-turning component configuration. Pagination suggests not to use literal value.
Note: After pagination.onChange is set, Table onChange no longer responds to pagination changes.
| Parameters | Instructions | Type | Default |
|---|---|---|---|
| currentPage | Current page number | number | - |
| defaultCurrentPage | Default current page number | number | 1 |
| formatPageText | Page-turning area copywriting custom formatting, pass false to close copywriting display; This item affects the copy display on the left of the page turning area of the form. It is different from the showTotal parameter of thePagination component. | boolean | ({ currentStart: number, currentEnd: number, total: number }) => string | true |
| pageSize | Number of entries per page | number | 10 |
| position | Location | 'bottom' | 'top' | 'both' | 'bottom' |
| total | Total number of entries | number | 0 |
| preventPageChangeOnPageSizeChange | Whether to prevent automatic adjustment of currentPage when pageSize changes. By default, when pageSize changes, the component automatically calculates the new currentPage to maintain the current data position. When set to true, the user controls the page change | boolean | false |
| onChange | Called when the page number or the page size changes; once set, the change event of Table no longer responds to pagination changes | (currentPage: number, pageSize: number) => void | |
| onPageChange | Called when the page number changes | (currentPage: number) => void | |
| onPageSizeChange | Called when the page size changes | (pageSize: number) => void |
For other configurations, see Pagination
Resizable
The parameters of the resizable object type, which mainly include event methods when the table column is scaled. These event methods can return an object that merges with the final column.
| Parameters | Instructions | Type | Default |
|---|---|---|---|
| handlerClassName | The class name added to the column while it is being resized | string | 'resizing' |
| onResize | Triggers when the table column changes its width | (column: Column) => Column | void | |
| onResizeStart | Triggers when the table column starts to change the width. | (column: Column) => Column | void | |
| onResizeStop | Triggers when the table column stops changing the width | (column: Column) => Column | void |
Methods
The methods exposed by Table can be accessed through the component ref, typed as TableHandle:
<script setup lang="ts">
import { onMounted, useTemplateRef } from 'vue';
import { Table } from '@fibrous/semi-ui-vue';
import type { TableHandle } from '@fibrous/semi-ui-vue';
const table = useTemplateRef<TableHandle>('table');
onMounted(() => {
table.value?.getCurrentPageData(); // => { dataSource: [/*...*/], groups: /*...*/ }
});
</script>
<template>
<Table ref="table" :columns="columns" :dataSource="dataSource" />
</template>
| Parameters | Instructions |
|---|---|
| getCurrentPageData() | Returns the data object of the current page: { dataSource: RecordType[], groups: Map<string | number, Set<string | number>> }, keyed by group key with the set of row keys in that group |
| scrollTo(offset) | Scrolls a virtualized table to the given pixel offset |
| scrollToItem(index, align?) | Scrolls a virtualized table to the given row, align is 'auto' | 'smart' | 'center' | 'start' | 'end' |
Accessibility
ARIA
Table follows the WAI-ARIA Table pattern: it is a static table, arrow keys do not move between cells, and every interactive part (sort, filter, expand, select) is a native control reachable with Tab.
- The table's role is table, rows are row, header cells are columnheader and cells are cell. A tree table is a table too and does not expose row levels
- The sort button is a native
buttonin the header cell, named by the column title. The sort direction isaria-sorton the header cell (ascendingordescending); unsorted columns do not carry it. TheshowSortTiptip shows when the button is focused - The expand button is a native
buttonnamed "Expand this row", witharia-expandedtelling whether the row is expanded - The row selection checkboxes have accessible names such as "Select this row" and "Select all rows"
- With a fixed header (
scroll.y,sticky) or virtualization, the header and the body render as two table elements; their common container has the table role and the inner tables have role none, so cells stay associated with their column headers - In a virtualized table
aria-rowcountis the header row count plus the total data row count, and data rows'aria-rowindexcontinues after the header rows, so screen readers announce rows that are not in the DOM
- The column filter button is a native
button: Tab focuses it, Enter, Space or Down Arrow opens the filter menu, and it carriesaria-haspopup="menu"andaria-expanded. Its name is "Filter data with this column", or "Filter this column, filter active" when a filter value is set. The#filterIconslot only replaces the icon inside the button, and the name and keyboard behavior of the button stay the same
Known limitations:
- In a sortable column the
titlerenders inside the sort button, so do not put buttons, links or other interactive content in it
RTL/LTR
- RTL default value of Table is controlled by ConfigProvider
- The align and fixed properties of the Table column will be automatically switched in RTL, left <-> right.
- Table tree data does not support RTL (Chrome and Safari browsers behave differently from Firefox)
Content Guidelines
- Table title
- The title of the table should clearly make the user perceive the purpose of the table;
- Add descriptions to complex tables to provide users with more contextual information about the table;
- use sentence case;
- Column headers
- Keep column headings concise, it is recommended to use 1-2 words as column headings;
- When the column header is long, it is recommended to display it in 2 lines, and the remaining text is abbreviated and displayed completely in the Tooltip;
- Adopt the capitalization rules of Sentence case;
- Use sentence case for column headings;
- Table operation area
- You can follow Button's content Guidelines
Design Tokens
| Sass variable | Value | Usage |
|---|---|---|
| $transition_duration-table_body-bg | var(--semi-transition_duration-none) | 表格-背景颜色-动画持续时间 |
| $transition_function-table_body-bg | var(--semi-transition_function-easeOut) | 表格-背景颜色-过渡曲线 |
| $transition_delay-table_body-bg | 0ms | 表格-背景颜色-延迟时间 |
| $transition_duration-table_row-head-bg | var(--semi-transition_duration-none) | 表格-行头-背景颜色-动画持续时间 |
| $transition_function-table_row-head-bg | linear | 表格-行头-背景颜色-过渡曲线 |
| $spacing-table-paddingY | $spacing-base | 表格空数据占位及虚拟列表分组垂直内边距 |
| $spacing-table-paddingX | $spacing-base-tight | 表格空数据占位及虚拟列表分组水平内边距 |
| $spacing-table_middle-paddingY | $spacing-base-tight | 中尺寸表格单元格垂直内边距 |
| $spacing-table_small-paddingY | $spacing-tight | 小尺寸表格单元格垂直内边距 |
| $spacing-table_title-paddingY | $spacing-base | 表格标题垂直内边距 |
| $spacing-table_title-paddingX | 0 | 表格标题水平内边距 |
| $spacing-table_footer-padding | $spacing-base | 表格 footer 内边距 |
| $spacing-table_expand_row-paddingLeft | 16px | 表格展开行左侧内边距 |
| $spacing-table_expand_row-paddingRight | 16px | 表格展开行右侧内边距 |
| $spacing-table_resizable-offset-y | 4px | 可拖动拉伸操作垂直偏移量 |
| $spacing-table_resizable-bottom | 4px | 可拖动拉伸操作底部距离 |
| $spacing-table_row_head-paddingY | $spacing-base-tight | 表头垂直内边距 |
| $spacing-table_row_head-paddingX | $spacing-base | 表头水平内边距 |
| $spacing-table_react_resizable_handle-right | -1px | 可拖动拉伸操作向右偏移量 |
| $spacing-table_tbody_rowCell-padding | $spacing-base | 表格体单元格内边距(默认尺寸) |
| $spacing-table_tbody_rowSelection_rowCell_notSelection-paddingX | 16px | 表格选择状态行(非复选框列)单元格水平内边距 |
| $spacing-table_tbody_rowSelection_rowCell_notSelection-paddingY | 10px | 表格选择状态行(非复选框列)垂直内边距 |
| $spacing-table_column_sorter-marginLeft | $spacing-extra-tight | 表头标题与排序按钮间距 |
| $spacing-table_column_filter-marginLeft | $spacing-extra-tight | 列过滤器按钮左侧外边距 |
| $spacing-table_bordered_titler-paddingLeft | $spacing-base | 带边框表格标题左侧内边距 |
| $spacing-table_bordered_titler-paddingRight | $spacing-base | 带边框表格标题右侧内边距 |
| $spacing-table_expand_icon-marginRight | 8px | 行展开按钮右侧外边距 |
| $spacing-table_panel_operation-paddingX | $spacing-base | 表格操作栏水平内边距 |
| $spacing-table_panel_operation-paddingY | $spacing-tight | 表格操作栏垂直内边距 |
| $width-table_base_border | 1px | 表格单元格分割线宽度 |
| $width-table_header_border | 1px | 表格表头分割线宽度 |
| $width-table_resizer_border | 2px | 表格拉伸列标示线宽度 |
| $width-table_column_selection | 48px | 表格选择列及展开列宽度 |
| $width-table_column_sorter-icon | 16px | 表格排序按钮宽度 |
| $height-table_column_sorter-icon | 16px | 表格排序按钮高度 |
| $width-table_column_filter-icon | 16px | 表格过滤按钮宽度 |
| $height-table_column_filter-icon | 16px | 表格过滤按钮高度 |
| $width-table_cell_fixed_left_last | 1px | 表格左侧固定列右侧分割线宽度 |
| $width-table_cell_fixed_right_first | 1px | 表格右侧固定列左侧分割线宽度 |
| $width-table_react_resizable_handle | 9px | 表格伸缩列调节热区宽度 |
| $height-table_pagination_outer_min | 60px | 表格分页器高度 |
| $height-table_column_filter_dropdown | 290px | 表格过滤筛选列表最大高度 |
| $color-table_panel-bg-default | var(--semi-color-primary) | 操作区域样式默认背景颜色 |
| $color-table_panel-text-default | var(--semi-color-primary-light-active) | 表格操作栏选中项文本颜色 |
| $color-table-bg-default | var(--semi-color-bg-1) | 表格固定列及吸顶表头背景颜色 |
| $color-table-text-default | var(--semi-color-text-0) | 单元格默认文字颜色 |
| $color-table-border-default | var(--semi-color-border) | 表格描边颜色 |
| $color-table_shadow-bg-default | rgb(from var(--semi-black) r g b / 0.08) | 表格滚动后阴影颜色 |
| $color-table_shadow-bg-dark | rgb(from var(--semi-black) r g b / 0.4) | 表格滚动后阴影颜色 - 暗色模式 |
| $color-table_shadow-border-default | var(--semi-color-border) | 表格拟阴影 描边颜色 |
| $color-table_th-bg-default | var(--semi-color-bg-1) | 表头背景底色,须不透明以遮住滚动到固定列和吸顶表头下的内容 |
| $color-table_th-fill-default | var(--semi-color-fill-0) | 表头背景叠加的填充色 |
| $color-table_th-border-default | var(--semi-color-border) | 表头底部分割线颜色 |
| $color-table_th-text-default | var(--semi-color-text-2) | 表头文字颜色 |
| $color-table_th-clickSort-bg-hover | var(--semi-color-fill-1) | 点击表头触发排序背景色 - 悬浮 |
| $color-table_pl-bg-default | transparent | |
| $color-table_body-bg-default | var(--semi-color-bg-1) | 表格行背景颜色 - 默认态 |
| $color-table_body-bg-hover | var(--semi-color-fill-0) | 表格行背景颜色 - 悬浮态 |
| $color-table_footer-bg-default | var(--semi-color-fill-0) | 表格 footer 背景颜色 - 默认 |
| $color-table_row_expanded-bg-default | var(--semi-color-fill-0) | 表格展开行背景颜色 - 默认 |
| $color-table_expanded_icon-default | var(--semi-color-text-2) | 表格展开行图标颜色 - 默认 |
| $color-table_expanded-bg-default | transparent | 表格展开行图标容器背景颜色 - 默认 |
| $color-table_filter_on-text-default | var(--semi-color-primary) | 表格过滤按钮颜色 - 激活态 |
| $color-table_filter-text-default | var(--semi-color-text-2) | 表格过滤按钮颜色 - 默认态 |
| $color-table_sorter_on-text-default | var(--semi-color-primary) | 表格排序按钮颜色 - 激活态 |
| $color-table_sorter-text-default | var(--semi-color-text-2) | 表格排序按钮颜色 - 默认态 |
| $color-table_sorter-text-hover | var(--semi-color-text-2) | 表格排序按钮颜色 - 悬浮态 |
| $color-table_page-text-default | var(--semi-color-text-2) | 表格翻页器文本颜色 |
| $color-table_resizer-bg-default | var(--semi-color-primary) | 表格拉伸标示线颜色 |
| $color-table_selection-bg-default | var(--semi-grey-0) | 表格分组背景色 |
| $color-table_placeholder-text-default | var(--semi-color-text-2) | 表格空数据文本颜色 |
| $color-table_cell-bg-hover | var(--semi-color-bg-0) | 让表格在 hover 时正确显示 $color-table_body-bg-hover 颜色,如无必要不要修改 |
| $font-table_base-fontSize | 14px | 表格默认文本字号 |
| $border-table_base-borderStyle | solid | 表格描边样式 |
| $width-table_fixed_shadow | 6px | 表格固定列滚动阴影宽度 |
| $z-table_fixed_column | $z-table-fixed | fixed列的zIndex值 |
FAQ
-
Clicking the row selection button on the second page will jump to the first page?
After the Table's dataSource is updated, the page number will be reset to the initial state. Please check if the data source changed when the component was rendered.
The Table of Vue compares the old and new
dataSourceitem by item: it is not reset when every item is still the original record, and it is reset when records are added or removed. Do not write a literal in the template, and do not regenerate the record objects on every render.<script setup lang="ts"> import { shallowRef } from 'vue'; const dataSource = shallowRef<Record<string, any>[]>([]); // replace the whole array only when needed const load = async () => { dataSource.value = await fetchData(); }; </script> <template> <!-- Wrong: every render creates new record objects --> <Table :dataSource="list.map((item) => ({ ...item }))" :columns="columns" /> </template> -
The number of filtered data is wrong?
Please check that your filter columns and data sources are configured correctly.
The filter column needs to set an independent
dataIndex, and the dataSource needs to set an independentkey. Please refer to thedataSourceAPI. Otherwise the filtering function will not work properly. -
Why is the table data not updated?
Vue tracks changes reactively: keep
dataSourcein areforshallowRef, and replacing the whole array or callingpush,spliceand similar methods triggers an update; with ashallowRef, changing a field of a record directly does not, so replace the whole array. The same goes forcolumns: usecomputedwhen it depends on reactive data, otherwise define it at the top level ofscript setup, and avoid literals written in the template. -
Why can't my form line be selected and expanded?
Please specify a rowKey or set a different "key" attribute for each item of the dataSource. All rows related operations in the table need to be used.
-
How to implement custom sorting or pass parameters to the server for sorting when clicking the sort button?
The input parameters of the onChange method include pagination, filters, and sorter. Users can customize the sorting of the dataSource according to the sorter.
-
How to add className to a row?
Use onRow or onHeaderRow.
-
How to style the table cell?
It can be controlled by column.onHeaderCell and column.onCell.
-
Why cache the previously selected keys for the first parameter of
rowSelectiononChange?This is for the scenario where the selected row keys are lost when data is selected on the first page during paging, and then the data is selected on the second page. If you don't want to use the cached keys, you can filter it from the current dataSource or use the second parameter of
rowSelectiononChange. -
Does it support single row selection?
Table currently does not support single-row selection function, and users can implement single selection in a custom way.