Table
Таблица показывает данные строками и колонками, а сортировку, выбор и страницы ведёт приложение.
Импорт
ts
import { Table, TableCaption, TableHeader, TableRow, TableHead, TableBody, TableCell } from '@prosper/ui'Анатомия
vue
<Table>
<TableCaption>…</TableCaption>
<TableHeader>
<TableRow>
<TableHead>…</TableHead>
</TableRow>
</TableHeader>
<TableBody>
<TableRow>
<TableCell>…</TableCell>
</TableRow>
</TableBody>
</Table>Примеры
По умолчанию
Шапка и три строки.
vue
<script setup lang="ts">
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@prosper/ui'
</script>
<template>
<Table aria-label="Участники команды">
<TableHeader>
<TableRow>
<TableHead>Имя</TableHead>
<TableHead>Роль</TableHead>
<TableHead>Почта</TableHead>
</TableRow>
</TableHeader>
<TableBody>
<TableRow>
<TableCell>Ольга Смирнова</TableCell>
<TableCell>Администратор</TableCell>
<TableCell>olga@example.com</TableCell>
</TableRow>
<TableRow>
<TableCell>Ирина Белова</TableCell>
<TableCell>Редактор</TableCell>
<TableCell>irina@example.com</TableCell>
</TableRow>
<TableRow>
<TableCell>Павел Ким</TableCell>
<TableCell>Наблюдатель</TableCell>
<TableCell>pavel@example.com</TableCell>
</TableRow>
</TableBody>
</Table>
</template>Размеры
Размеры md и sm.
vue
<script setup lang="ts">
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
tableSizes,
} from '@prosper/ui'
</script>
<template>
<div
style="
display: flex;
flex-direction: column;
gap: var(--prosper-spacing-xl);
"
>
<Table
v-for="size in tableSizes"
:key="size"
:size="size"
:aria-label="`Размер ${size}`"
>
<TableHeader>
<TableRow>
<TableHead>Имя</TableHead>
<TableHead>Роль</TableHead>
</TableRow>
</TableHeader>
<TableBody>
<TableRow>
<TableCell>Ольга Смирнова</TableCell>
<TableCell>Администратор</TableCell>
</TableRow>
<TableRow>
<TableCell>Павел Ким</TableCell>
<TableCell>Наблюдатель</TableCell>
</TableRow>
</TableBody>
</Table>
</div>
</template>Полосы
Нечётные строки тела окрашены, поэтому наведение и выбор на них не видны.
vue
<script setup lang="ts">
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@prosper/ui'
const people = [
{ name: 'Ольга Смирнова', role: 'Администратор' },
{ name: 'Ирина Белова', role: 'Редактор' },
{ name: 'Павел Ким', role: 'Наблюдатель' },
{ name: 'Асель Нурова', role: 'Редактор' },
]
</script>
<template>
<Table divider="stripes" aria-label="Участники команды с полосами">
<TableHeader>
<TableRow>
<TableHead>Имя</TableHead>
<TableHead>Роль</TableHead>
</TableRow>
</TableHeader>
<TableBody>
<TableRow v-for="person in people" :key="person.name">
<TableCell>{{ person.name }}</TableCell>
<TableCell>{{ person.role }}</TableCell>
</TableRow>
</TableBody>
</Table>
</template>Типы ячеек
AvatarLabelGroup в обёртке с минимальной шириной, чтобы имя и почта не переносились по буквам, бейдж, полоса прогресса, кнопки и меню действий, а широкая таблица прокручивается внутри обёртки.
vue
<script setup lang="ts">
import {
Avatar,
AvatarFallback,
AvatarLabelGroup,
AvatarLabelGroupDescription,
AvatarLabelGroupName,
Badge,
Button,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
IconButton,
ProgressBar,
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@prosper/ui'
import { DotsVertical, Trash01 } from '@prosper/ui/icons'
const projects = [
{
owner: 'Ольга Смирнова',
initials: 'ОС',
email: 'olga@example.com',
status: 'Активен',
color: 'success',
progress: 80,
},
{
owner: 'Павел Ким',
initials: 'ПК',
email: 'pavel@example.com',
status: 'На паузе',
color: 'warning',
progress: 35,
},
] as const
</script>
<template>
<Table aria-label="Проекты">
<TableHeader>
<TableRow>
<TableHead>Владелец</TableHead>
<TableHead>Статус</TableHead>
<TableHead>Прогресс</TableHead>
<TableHead>Действия</TableHead>
</TableRow>
</TableHeader>
<TableBody>
<TableRow v-for="project in projects" :key="project.owner">
<TableCell>
<div
style="
min-inline-size: calc(
var(--prosper-space-48) + var(--prosper-spacing-xl)
);
"
>
<AvatarLabelGroup size="md">
<Avatar>
<AvatarFallback>{{ project.initials }}</AvatarFallback>
</Avatar>
<AvatarLabelGroupName>{{ project.owner }}</AvatarLabelGroupName>
<AvatarLabelGroupDescription>
{{ project.email }}
</AvatarLabelGroupDescription>
</AvatarLabelGroup>
</div>
</TableCell>
<TableCell>
<Badge :color="project.color">{{ project.status }}</Badge>
</TableCell>
<TableCell>
<div style="min-inline-size: 10rem">
<ProgressBar
:value="project.progress"
label-position="right"
:aria-label="`Прогресс: ${project.owner}`"
/>
</div>
</TableCell>
<TableCell>
<div
style="
display: flex;
align-items: center;
gap: var(--prosper-spacing-md);
"
>
<Button variant="secondary" size="sm">Открыть</Button>
<IconButton
variant="tertiary"
size="sm"
:aria-label="`Удалить: ${project.owner}`"
>
<Trash01 />
</IconButton>
<DropdownMenu>
<DropdownMenuTrigger as-child>
<IconButton
variant="tertiary"
size="sm"
:aria-label="`Меню: ${project.owner}`"
>
<DotsVertical />
</IconButton>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem>Редактировать</DropdownMenuItem>
<DropdownMenuItem>Дублировать</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</TableCell>
</TableRow>
</TableBody>
</Table>
</template>Действия
Отступы в начале и конце отдельной TableCell задают её переменные из раздела «Настройка».
vue
<script setup lang="ts">
import { ref } from 'vue'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
IconButton,
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
tableSizes,
} from '@prosper/ui'
import {
Copy01,
DotsVertical,
DownloadCloud02,
Edit01,
Trash01,
} from '@prosper/ui/icons'
const actions = [
{ icon: Copy01, label: 'Копировать' },
{ icon: DownloadCloud02, label: 'Скачать' },
{ icon: Trash01, label: 'Удалить' },
{ icon: Edit01, label: 'Редактировать' },
]
const lastAction = ref('')
</script>
<template>
<div style="display: grid; gap: var(--prosper-spacing-xl); inline-size: 100%">
<Table
v-for="size in tableSizes"
:key="size"
:size="size"
:aria-label="`Документы, размер ${size}`"
>
<TableHeader>
<TableRow>
<TableHead>Документ</TableHead>
<TableHead class="action-column">Действия</TableHead>
<TableHead class="action-column">
<span style="position: absolute; clip-path: inset(50%)">
Меню действий
</span>
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
<TableRow>
<TableCell>Отчёт за октябрь</TableCell>
<TableCell class="action-column utility-cell">
<div style="display: inline-flex; gap: var(--prosper-spacing-xxs)">
<IconButton
v-for="action in actions"
:key="action.label"
variant="tertiary"
size="xs"
:aria-label="action.label"
@click="lastAction = action.label"
>
<component :is="action.icon" />
</IconButton>
</div>
</TableCell>
<TableCell
class="action-column menu-cell"
:class="{ 'menu-cell-small': size === 'sm' }"
>
<DropdownMenu>
<DropdownMenuTrigger as-child>
<IconButton
variant="tertiary"
size="md"
aria-label="Меню действий"
>
<DotsVertical />
</IconButton>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem @select="lastAction = 'Открыть'">
Открыть
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</TableCell>
</TableRow>
</TableBody>
</Table>
</div>
<p role="status">
<template v-if="lastAction">Выбрано действие «{{ lastAction }}»</template>
</p>
</template>
<style scoped>
.action-column {
inline-size: 1%;
white-space: nowrap;
}
.utility-cell {
--prosper-table-cell-padding-inline-start: var(--prosper-spacing-xl);
--prosper-table-cell-padding-inline-end: var(--prosper-spacing-xl);
}
.menu-cell {
--prosper-table-cell-padding-inline-start: var(--prosper-spacing-md);
--prosper-table-cell-padding-inline-end: var(--prosper-spacing-md);
}
.menu-cell-small {
--prosper-table-cell-padding-inline-end: var(--prosper-spacing-xs);
}
</style>Пустая таблица
Одна ячейка с colspan на всю ширину вместо строк.
vue
<script setup lang="ts">
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@prosper/ui'
</script>
<template>
<Table aria-label="Участники команды без данных">
<TableHeader>
<TableRow>
<TableHead>Имя</TableHead>
<TableHead>Роль</TableHead>
<TableHead>Почта</TableHead>
</TableRow>
</TableHeader>
<TableBody>
<TableRow>
<TableCell colspan="3" style="text-align: center">
Участников пока нет
</TableCell>
</TableRow>
</TableBody>
</Table>
</template>Сортировка
Сортируется одна колонка за раз: приложение хранит ключ и направление в ref.
vue
<script setup lang="ts">
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
type TableSort,
} from '@prosper/ui'
import { computed, ref } from 'vue'
type Key = 'name' | 'role' | 'joined'
const columns: { key: Key; label: string }[] = [
{ key: 'name', label: 'Имя' },
{ key: 'role', label: 'Роль' },
{ key: 'joined', label: 'Дата' },
]
const people = [
{ name: 'Ольга Смирнова', role: 'Администратор', joined: '2024-03-12' },
{ name: 'Ирина Белова', role: 'Редактор', joined: '2023-11-02' },
{ name: 'Павел Ким', role: 'Наблюдатель', joined: '2025-01-20' },
{ name: 'Асель Нурова', role: 'Редактор', joined: '2024-08-05' },
]
const active = ref<{ key: Key; direction: TableSort }>({
key: 'name',
direction: 'ascending',
})
const sortOf = (key: Key): TableSort =>
active.value.key === key ? active.value.direction : 'none'
const sortBy = (key: Key, direction: TableSort): void => {
active.value = { key, direction }
}
const rows = computed(() => {
const { key, direction } = active.value
if (direction === 'none') return people
const sign = direction === 'ascending' ? 1 : -1
return [...people].sort(
(first, second) => sign * first[key].localeCompare(second[key], 'ru'),
)
})
</script>
<template>
<Table aria-label="Участники команды с сортировкой">
<TableHeader>
<TableRow>
<TableHead
v-for="column in columns"
:key="column.key"
:sort="sortOf(column.key)"
@update:sort="sortBy(column.key, $event)"
>
{{ column.label }}
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
<TableRow v-for="person in rows" :key="person.name">
<TableCell>{{ person.name }}</TableCell>
<TableCell>{{ person.role }}</TableCell>
<TableCell>{{ person.joined }}</TableCell>
</TableRow>
</TableBody>
</Table>
</template>Выбор строк
Чекбокс в первой ячейке выбирает строку, а чекбокс в шапке с indeterminate выбирает все.
vue
<script setup lang="ts">
import {
Checkbox,
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@prosper/ui'
import { computed, ref } from 'vue'
const people = [
{ id: 1, name: 'Ольга Смирнова', role: 'Администратор' },
{ id: 2, name: 'Ирина Белова', role: 'Редактор' },
{ id: 3, name: 'Павел Ким', role: 'Наблюдатель' },
]
const selected = ref<number[]>([2])
const all = computed(() => selected.value.length === people.length)
const some = computed(() => selected.value.length > 0)
const setAll = (checked: boolean): void => {
selected.value = checked ? people.map(({ id }) => id) : []
}
const setOne = (id: number, checked: boolean): void => {
selected.value = checked
? [...selected.value, id]
: selected.value.filter((value) => value !== id)
}
</script>
<template>
<Table aria-label="Участники команды с выбором">
<TableHeader>
<TableRow>
<TableHead>
<template #leading>
<Checkbox
aria-label="Выбрать всех"
:checked="all"
:indeterminate="some && !all"
@update:checked="setAll"
/>
</template>
Имя
</TableHead>
<TableHead>Роль</TableHead>
</TableRow>
</TableHeader>
<TableBody>
<TableRow
v-for="person in people"
:key="person.id"
:selected="selected.includes(person.id)"
>
<TableCell>
<template #leading>
<Checkbox
:aria-label="`Выбрать: ${person.name}`"
:checked="selected.includes(person.id)"
@update:checked="setOne(person.id, $event)"
/>
</template>
{{ person.name }}
</TableCell>
<TableCell>{{ person.role }}</TableCell>
</TableRow>
</TableBody>
</Table>
</template>Карточка
Card с заголовком, бейджем и линией держит Table, а Pagination стоит под таблицей отдельной строкой.
vue
<script setup lang="ts">
import {
Badge,
Button,
ButtonIcon,
Card,
CardDivider,
CardHeader,
CardHeaderContent,
CardHeaderHeading,
CardHeaderTitle,
Checkbox,
Pagination,
PaginationNext,
PaginationPrev,
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@prosper/ui'
import { ArrowLeft, ArrowRight } from '@prosper/ui/icons'
import { computed, ref } from 'vue'
const people = [
{ id: 1, name: 'Ольга Смирнова', role: 'Администратор' },
{ id: 2, name: 'Ирина Белова', role: 'Редактор' },
{ id: 3, name: 'Павел Ким', role: 'Наблюдатель' },
{ id: 4, name: 'Асель Нурова', role: 'Редактор' },
{ id: 5, name: 'Данияр Сатыбалдин', role: 'Администратор' },
{ id: 6, name: 'Мария Орлова', role: 'Наблюдатель' },
]
const perPage = 3
const page = ref(1)
const selected = ref<number[]>([2])
const pageCount = Math.ceil(people.length / perPage)
const rows = computed(() =>
people.slice((page.value - 1) * perPage, page.value * perPage),
)
const allSelected = computed(() =>
rows.value.every(({ id }) => selected.value.includes(id)),
)
const someSelected = computed(() =>
rows.value.some(({ id }) => selected.value.includes(id)),
)
const setAll = (checked: boolean): void => {
const ids = rows.value.map(({ id }) => id)
selected.value = checked
? [...new Set([...selected.value, ...ids])]
: selected.value.filter((value) => !ids.includes(value))
}
const setOne = (id: number, checked: boolean): void => {
selected.value = checked
? [...selected.value, id]
: selected.value.filter((value) => value !== id)
}
</script>
<template>
<Card style="inline-size: 100%">
<CardHeader>
<CardHeaderContent>
<CardHeaderHeading>
<CardHeaderTitle id="team-card-title">
Участники команды
<Badge size="sm">{{ people.length }} человек</Badge>
</CardHeaderTitle>
</CardHeaderHeading>
</CardHeaderContent>
<CardDivider />
</CardHeader>
<Table aria-labelledby="team-card-title">
<TableHeader>
<TableRow>
<TableHead>
<template #leading>
<Checkbox
aria-label="Выбрать всех"
:checked="allSelected"
:indeterminate="someSelected && !allSelected"
@update:checked="setAll"
/>
</template>
Имя
</TableHead>
<TableHead>Роль</TableHead>
</TableRow>
</TableHeader>
<TableBody>
<TableRow
v-for="person in rows"
:key="person.id"
:selected="selected.includes(person.id)"
>
<TableCell>
<template #leading>
<Checkbox
:aria-label="`Выбрать: ${person.name}`"
:checked="selected.includes(person.id)"
@update:checked="setOne(person.id, $event)"
/>
</template>
{{ person.name }}
</TableCell>
<TableCell>{{ person.role }}</TableCell>
</TableRow>
</TableBody>
</Table>
<Pagination
v-model:page="page"
class="footer"
:total="people.length"
:items-per-page="perPage"
>
<PaginationPrev as-child>
<Button class="wide" variant="secondary" size="sm">
<ButtonIcon><ArrowLeft /></ButtonIcon>
Назад
</Button>
</PaginationPrev>
<PaginationPrev as-child>
<Button
class="narrow"
variant="secondary"
size="sm"
aria-label="Предыдущая страница"
>
<ButtonIcon align="only"><ArrowLeft /></ButtonIcon>
</Button>
</PaginationPrev>
<span>Страница {{ page }} из {{ pageCount }}</span>
<PaginationNext as-child>
<Button class="wide" variant="secondary" size="sm">
Вперёд
<ButtonIcon align="end"><ArrowRight /></ButtonIcon>
</Button>
</PaginationNext>
<PaginationNext as-child>
<Button
class="narrow"
variant="secondary"
size="sm"
aria-label="Следующая страница"
>
<ButtonIcon align="only"><ArrowRight /></ButtonIcon>
</Button>
</PaginationNext>
</Pagination>
</Card>
</template>
<style scoped>
.footer {
justify-content: space-between;
border-block-start: 1px solid var(--prosper-color-border-secondary);
padding: var(--prosper-spacing-lg) var(--prosper-spacing-3xl)
var(--prosper-spacing-xl);
}
.narrow {
display: none;
}
@container prosper (width < 40rem) {
.footer {
padding-inline: var(--prosper-spacing-xl);
}
.wide {
display: none;
}
.narrow {
display: inline-flex;
}
}
</style>API
Table
Корень таблицы: обёртка с прокруткой и нативная table внутри, которой нужно имя; class, style и onScroll ложатся на обёртку, остальные атрибуты на table.
Props
| Имя | Тип | По умолчанию | Описание |
|---|---|---|---|
size | 'md' | 'sm' | 'md' | Размер строк и отступов: md или sm. |
divider | 'line' | 'stripes' | 'line' | Разделение строк: line рисует линии, stripes красит нечётные строки тела. |
Слоты
| Имя | Тип | Описание |
|---|---|---|
default | {} | Части таблицы: TableCaption, TableHeader и TableBody. |
TableCaption
Подпись таблицы; видимой или скрытой её делает класс потребителя.
Слоты
| Имя | Тип | Описание |
|---|---|---|
default | {} | Текст подписи. |
TableHeader
Шапка таблицы: thead со строками заголовков.
Слоты
| Имя | Тип | Описание |
|---|---|---|
default | {} | Строки TableRow с заголовками TableHead. |
TableRow
Строка таблицы: tr с видом наведения и выбора.
Props
| Имя | Тип | По умолчанию | Описание |
|---|---|---|---|
selected | boolean | — | Строка выбрана: заливка как при наведении, а выбранность для скринридера передаёт чекбокс в строке. |
Слоты
| Имя | Тип | Описание |
|---|---|---|
default | {} | Ячейки TableHead или TableCell. |
TableHead
Заголовок колонки: th с scope="col", при заданном sort с кнопкой сортировки.
Props
| Имя | Тип | По умолчанию | Описание |
|---|---|---|---|
sort | 'ascending' | 'descending' | 'none' | — | Направление сортировки колонки: без значения колонка не сортируется. |
События
| Имя | Тип | Описание |
|---|---|---|
update:sort | (value: "none" | "ascending" | "descending") => void | Нажатие на кнопку сортировки или на стрелку: событие несёт следующее значение цикла none, ascending, descending. |
Слоты
| Имя | Тип | Описание |
|---|---|---|
leading | {} | Содержимое перед подписью, например Checkbox выбора всех строк; стоит вне кнопки сортировки. |
default | {} | Подпись колонки. |
trailing | {} | Значок после подписи, например HelpButton. |
TableBody
Тело таблицы: tbody со строками данных.
Слоты
| Имя | Тип | Описание |
|---|---|---|
default | {} | Строки TableRow с ячейками TableCell. |
TableCell
Ячейка данных: td с видом таблицы.
Слоты
| Имя | Тип | Описание |
|---|---|---|
leading | {} | Содержимое перед основным, например Checkbox выбора строки. |
default | {} | Содержимое ячейки: текст или компоненты кита. |
Доступность
| Клавиша | Действие |
|---|---|
| Tab | Фокус на кнопку сортировки и на обёртку, когда таблица шире неё |
| Enter, Пробел | Сменить сортировку колонки |
| Стрелки влево и вправо | Прокрутить обёртку в фокусе |
- Таблица нативная:
table,thead,tbody,th scope="col"иtd, как в шаблоне Table WAI-ARIA APG. - Таблице нужно имя из
aria-label,aria-labelledbyилиTableCaption, иначе в режиме разработки будет предупреждение. - Когда таблица шире обёртки, обёртка становится областью
regionсtabindex="0"и тем же именем, чтобы её можно было прокрутить клавишами. - Заголовок отсортированной колонки несёт
aria-sort, а кнопка сортировки называется подписью колонки.
Настройка
| Переменная | Назначение |
|---|---|
--prosper-table-cell-padding-inline-start | Отступ в начале ячейки TableCell |
--prosper-table-cell-padding-inline-end | Отступ в конце ячейки TableCell |