Data Table
This is an in-depth guide on how to use the NvDatatable component, covering column configuration, custom cell rendering, pagination modes, and best practices. For API documentation and interactive examples, see the component documentation.
Key Features
- Custom Cell Renderers: Full control over cell content with custom render functions using Vue's
h()for complex visualizations and interactions - Full TypeScript Support: Comprehensive type definitions with generic row typing via factory function pattern for complete type safety
- Three Pagination Modes: Client-side, server-side, and infinite scroll pagination support
- Extensive Column Configuration: Control width, resizing, hiding, and custom headers with flexible configuration options
- Built on TanStack Table: Leverages the industry-standard TanStack Vue Table library for robust, performant data management
Basic Usage
The simplest implementation requires only column definitions and row data:
<template>
<EmployeeDatatable :columns="columns" :rows="rows" />
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { createNvDatatable, makeColumn } from '@nova-design-system/nova-vue';
// Define interface for rows
interface Employee {
id: number;
name: string;
email: string;
department: string;
salary: number;
}
// Create typed datatable component
const EmployeeDatatable = createNvDatatable<Employee>();
// Create column factory
const col = makeColumn<Employee>();
// Define columns
const columns = ref([
col({ field: 'name', headerName: 'Full Name' }),
col({ field: 'email', headerName: 'Email Address' }),
col({ field: 'department', headerName: 'Department' }),
col({ field: 'salary', headerName: 'Salary' }),
]);
// Define rows
const rows = ref<Employee[]>([
{
id: 1,
name: 'John Smith',
email: 'john.smith@company.com',
department: 'Engineering',
salary: 75000,
},
// ... more data
]);
</script>
Advanced Column Configuration
Columns support extensive configuration options for precise control. View the full column configuration reference for details.
<template>
<ProductDatatable :columns="columns" :rows="rows">
<template #cell-name="{ value }">
<div class="font-semibold">{{ value }}</div>
</template>
<template #cell-price="{ value }">
<span class="font-mono text-feedback-success-low">
${{ typeof value === 'number' ? value.toFixed(2) : '0.00' }}
</span>
</template>
<template #cell-status="{ value }">
<NvBadge
:label="value"
:color="value === 'active' ? 'success' : 'error'"
/>
</template>
</ProductDatatable>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { createNvDatatable, makeColumn } from '@nova-design-system/nova-vue';
import { NvBadge } from '@nova-design-system/nova-vue';
const ProductDatatable = createNvDatatable<Product>();
const col = makeColumn<Product>(); // Column factory
const advancedColumns = ref([
col({
field: 'name',
headerName: 'Product Name',
width: 200,
resizable: true,
}),
col({
field: 'price',
headerName: 'Price',
width: 120,
// Format number to currency string
valueFormatter: ({ value }) => `$${value.toFixed(2)}`,
}),
col({
field: 'status',
headerName: 'Status',
// No width specified - this column will take remaining space
}),
]);
const rows = ref<Product[]>([
{
id: 1,
name: 'Laptop Pro',
price: 1299.99,
status: 'active',
},
// ... more data
]);
</script>
Typescript
The NvDatatable component provides full TypeScript support with automatic type inference using the makeColumn factory function. This ensures type safety throughout your column definitions, especially when using valueFormatter and renderCell.
Using makeColumn Factory
The recommended approach is to use the makeColumn factory function:
<script setup lang="ts">
import { ref } from 'vue';
import { createNvDatatable, makeColumn } from '@nova-design-system/nova-vue';
// Define your data interface
interface Employee {
id: number;
name: string;
email: string;
salary: number;
isActive: boolean;
}
// Create typed datatable component
const EmployeeDatatable = createNvDatatable<Employee>();
// Create a column factory for your data type
const col = makeColumn<Employee>();
// Define columns with full type safety
const columns = ref([
col({ field: 'id', headerName: 'ID' }),
col({ field: 'name', headerName: 'Name' }),
col({ field: 'email', headerName: 'Email' }),
col({ field: 'salary', headerName: 'Salary' }),
]);
// Use with your data
const employees = ref<Employee[]>([
{ id: 1, name: 'John Doe', email: 'john@example.com', salary: 75000, isActive: true },
{ id: 2, name: 'Jane Smith', email: 'jane@example.com', salary: 85000, isActive: true },
]);
</script>
Type Flow with valueFormatter
The makeColumn factory ensures that when you use valueFormatter, the return type automatically flows to renderCell:
<script setup lang="ts">
import { h } from 'vue';
interface Employee {
id: number;
name: string;
salary: number; // number type
}
const col = makeColumn<Employee>();
const columns = ref([
col({
field: 'salary',
headerName: 'Salary',
// valueFormatter receives number, returns string
valueFormatter: ({ value }) => `$${value.toLocaleString()}`,
// renderCell receives the formatted string (not the original number)
renderCell: ({ value }) => h('span', { class: 'font-mono' }, value)
// 'value' is typed as string ✓
}),
]);
</script>
Complex Data Types
The factory function works seamlessly with complex data types like objects and arrays:
<script setup lang="ts">
interface User {
id: number;
name: { first: string; last: string };
skills: string[];
}
const col = makeColumn<User>();
const columns = ref([
col({
field: 'name',
headerName: 'Full Name',
// Transform nested object to string
valueFormatter: ({ value }) => `${value.first} ${value.last}`,
}),
col({
field: 'skills',
headerName: 'Skills',
// Transform array to string
valueFormatter: ({ value }) => value.join(', '),
}),
]);
</script>
Automatic Column Generation
When you don't provide column definitions, NvDatatable inspects the row data and builds the columns for you. This is handy for quickly displaying data without wiring up a column for every field.
const AutoDatatable = createNvDatatable<Employee>();
const rows = [
{ id: 1, firstName: 'Ada Lovelace', salary: 95000, isActive: true, startDate: '2021-03-15' },
{ id: 2, firstName: 'Alan Turing', salary: 88000, isActive: false, startDate: '2022-07-01' },
];
<!-- Omit :columns — the datatable infers them from the row data -->
<AutoDatatable :rows="rows" :sorting="{}" />
The generated columns follow these rules:
- One column per key found in the data (the union of keys across the first rows, in first-seen order).
- Headers are humanized from field names —
firstNamebecomes "First Name",created_atbecomes "Created At". - Cells are rendered based on the inferred value type:
- Boolean → centered
True/Falsetext - Number → right-aligned
- Date (a
Datevalue or ISO date string) → locale-formatted - Object / array → compact JSON
- String → rendered as-is
- Boolean → centered
- Sorting and filtering keep operating on the raw underlying values, not the formatted display text.
- Explicit columns always take precedence — pass
columnsto override any or all of the generated columns.
Tip: You can control cell alignment on any column (generated or explicit) with the
alignproperty:'left' | 'center' | 'right'.
Columns
Each column definition supports the following properties:
| Property | Required | Type | Description |
|---|---|---|---|
field | ✅ | keyof Row | The key from your data object to display |
headerName | - | string | Custom header text (defaults to field name) |
width | - | number | Column width in pixels |
align | - | 'left' | 'center' | 'right' | Horizontal alignment of the column's cell content. Explicit columns default to left; auto-generated columns default to center (numbers right-aligned) |
resizable | - | boolean | Whether users can resize the column (default: true) |
hidden | - | boolean | Hide the column from display |
valueFormatter | - | function | Transform the raw value before rendering |
renderCell | - | function | Custom cell rendering function using Vue's h() |
renderHeader | - | function | Custom header rendering function using Vue's h() |
Value Formatters
The valueFormatter function transforms raw cell values before rendering, providing a clean way to handle common data transformations without requiring full render functions.
When to Use valueFormatter vs renderCell
- Use
valueFormatterwhen you need to transform data to a different format (dates, arrays, nested objects) but don't need custom Vue components or styling - Use
renderCellwhen you need custom presentation with styled components, badges, buttons, or complex layouts - Use both together to first transform the data with
valueFormatter, then style it withrenderCell
Function Signature
valueFormatter?: (params: NvTableValueFormatterParams<Row, Row[K], K>) => F
Function Parameters:
The function receives a single params object with the following properties:
| Parameter | Type | Description |
|---|---|---|
value | Row[K] | The raw cell value from the data |
row | Row | The complete row object (useful for accessing other fields) |
field | K | The field name being formatted |
Returns: Any type F that will be passed to renderCell. The return type is inferred from your function and automatically typed in renderCell.
Common Use Cases
Format Dates:
<script setup lang="ts">
const col = makeColumn<Employee>();
const columns = ref([
col({
field: 'birthDate',
headerName: 'Birth Date',
valueFormatter: ({ value }) => {
if (typeof value === 'string') {
return new Date(value).toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
});
}
return '';
},
}),
]);
</script>
Join Arrays:
<script setup lang="ts">
const col = makeColumn<Employee>();
const columns = ref([
col({
field: 'skills',
headerName: 'Skills',
valueFormatter: ({ value }) => {
if (Array.isArray(value)) {
return value.join(', ');
}
return '';
},
}),
]);
</script>
Access Nested Objects:
<script setup lang="ts">
const col = makeColumn<Employee>();
const columns = ref([
col({
field: 'person',
headerName: 'Full Name',
valueFormatter: ({ value }) => {
if (typeof value === 'object' && value !== null) {
const person = value as { first: string; last: string };
return `${person.first} ${person.last}`;
}
return '';
},
}),
]);
</script>
Combining valueFormatter with renderCell
You can use both together - the valueFormatter runs first to transform the data, then renderCell handles the presentation:
<script setup lang="ts">
import { h } from 'vue';
import { NvBadge } from '@nova-design-system/nova-vue';
const col = makeColumn<Employee>();
const columns = ref([
col({
field: 'isActive',
headerName: 'Status',
// First, format the boolean to a string
valueFormatter: ({ value }) => (value ? 'Active' : 'Inactive'),
// Then, style it with a badge
renderCell: ({ value }) => {
return h(NvBadge, {
label: String(value),
color: value === 'Active' ? 'success' : 'neutral',
});
},
}),
]);
</script>
Combining valueFormatter with Scoped Slots
The formatted value automatically flows to scoped slots:
<template>
<EmployeeDatatable :columns="columns" :rows="employees">
<!-- Slot receives FORMATTED value (string) -->
<template #cell-skills="{ value }">
<div class="text-sm">{{ value }}</div>
<!-- value is "JavaScript, React, TypeScript", not an array -->
</template>
</EmployeeDatatable>
</template>
<script setup lang="ts">
const col = makeColumn<Employee>();
const columns = ref([
col({
field: 'skills', // Array type: string[]
valueFormatter: ({ value }) => value.join(', '), // Returns string
// Slot receives the string, not the array
}),
]);
</script>
Custom Cell Renderers
There are two ways to customize cell rendering: scoped slots (recommended) or render functions.
Option 1: Scoped Slots (Recommended)
Use scoped slots for clean, template-based cell customization. Each column can have its own slot using the naming pattern #cell-{fieldName}.
Slot Parameters:
| Parameter | Type | Description |
|---|---|---|
value | Row[K] | The cell's actual value (after valueFormatter if provided) |
row | Row | Complete row object for accessing other fields |
field | K | The field name being rendered |
rowIndex | number | Zero-based row index |
Examples:
<template>
<ProductDatatable :columns="columns" :rows="products">
<!-- Format currency -->
<template #cell-price="{ value }">
<span class="font-mono">
${{ typeof value === 'number' ? value.toFixed(2) : '0.00' }}
</span>
</template>
<!-- Status badge -->
<template #cell-status="{ value }">
<NvBadge
:label="value"
:color="value === 'active' ? 'success' : 'error'"
/>
</template>
<!-- Actions with access to full row -->
<template #cell-id="{ row }">
<NvButton @click="editProduct(row)">Edit</NvButton>
<NvButton @click="deleteProduct(row)">Delete</NvButton>
</template>
</ProductDatatable>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { createNvDatatable, makeColumn } from '@nova-design-system/nova-vue';
import { NvBadge, NvButton } from '@nova-design-system/nova-vue';
const ProductDatatable = createNvDatatable<Product>();
const col = makeColumn<Product>();
// Simple column definitions - no renderCell needed!
const columns = ref([
col({ field: 'name', headerName: 'Product Name' }),
col({ field: 'price', headerName: 'Price' }),
col({ field: 'status', headerName: 'Status' }),
col({ field: 'id', headerName: 'Actions' }),
]);
</script>
Typing Scoped Slots
By default, slot parameters like value are typed as any in Vue. To get full TypeScript type safety and autocomplete, use the NvDatatableSlotProps type helper.
Type Definition:
NvDatatableSlotProps<Row, K extends keyof Row, F = Row[K]>
| Type Parameter | Description |
|---|---|
Row | Your row data type (e.g., Employee, Product) |
K | The field key from your row type (e.g., 'name', 'price') |
F | The formatted value type (defaults to Row[K], or specify the valueFormatter return type) |
Option 1: Type Aliases (Recommended)
Create reusable type aliases for your slot props. This is the most maintainable approach:
<script setup lang="ts">
import {
createNvDatatable,
makeColumn,
type NvDatatableSlotProps,
} from '@nova-design-system/nova-vue';
interface Employee {
id: number;
name: string;
salary: number;
isActive: boolean;
}
// Define typed slot props
type NameSlotProps = NvDatatableSlotProps<Employee, 'name', string>;
type SalarySlotProps = NvDatatableSlotProps<Employee, 'salary', string>;
type StatusSlotProps = NvDatatableSlotProps<Employee, 'isActive', string>;
type ActionsSlotProps = NvDatatableSlotProps<Employee, 'id', number>;
const EmployeeDatatable = createNvDatatable<Employee>();
const col = makeColumn<Employee>();
const columns = ref([
col({ field: 'name', headerName: 'Name' }),
col({
field: 'salary',
headerName: 'Salary',
valueFormatter: ({ value }) => `$${value.toLocaleString()}`,
// Returns string, so F = string in slot
}),
col({
field: 'isActive',
headerName: 'Status',
valueFormatter: ({ value }) => (value ? 'Active' : 'Inactive'),
// Returns string, so F = string in slot
}),
col({ field: 'id', headerName: 'Actions' }),
]);
</script>
<template>
<EmployeeDatatable :columns="columns" :rows="employees">
<!-- ✅ value is typed as string -->
<template #cell-name="{ value, row }: NameSlotProps">
<div class="font-semibold">{{ value }}</div>
</template>
<!-- ✅ value is typed as string (from valueFormatter) -->
<template #cell-salary="{ value }: SalarySlotProps">
<span class="font-mono">{{ value }}</span>
</template>
<!-- ✅ value is typed as string (from valueFormatter) -->
<template #cell-isActive="{ value }: StatusSlotProps">
<NvBadge
:label="value"
:color="value === 'Active' ? 'success' : 'error'"
/>
</template>
<!-- ✅ row is fully typed as Employee -->
<template #cell-id="{ row }: ActionsSlotProps">
<NvButton @click="handleEdit(row.id)">Edit</NvButton>
</template>
</EmployeeDatatable>
</template>
Option 2: Inline Typing
For simpler use cases, type the slot props inline:
<template>
<EmployeeDatatable :columns="columns" :rows="employees">
<template
#cell-salary="{ value }: NvDatatableSlotProps<Employee, 'salary', string>"
>
<span class="font-mono">{{ value }}</span>
</template>
</EmployeeDatatable>
</template>
Option 2: Render Functions
Use render functions when you need programmatic logic or when working in render function contexts.
Function Signature
renderCell?: (
params: NvTableRenderCellParams<Row, F, K>,
) => VNode | string | number;
| Parameter | Type | Description |
|---|---|---|
value | Row[K] | The cell's actual value (after valueFormatter if provided) |
row | Row | Complete row object for accessing other fields |
field | K | The field name being rendered |
rowIndex | number | Zero-based row index |
Examples:
<script setup lang="ts">
import { h } from 'vue';
import { makeColumn } from '@nova-design-system/nova-vue';
import { NvBadge } from '@nova-design-system/nova-vue';
const col = makeColumn<Product>();
const columns = ref([
col({
field: 'price',
renderCell: ({ value }) => {
return h('span', { class: 'font-mono' },
`$${typeof value === 'number' ? value.toLocaleString() : '0'}`);
},
}),
col({
field: 'status',
renderCell: ({ value }) => {
return h(NvBadge, {
label: value,
color: getStatusColor(value),
});
},
}),
]);
</script>
Priority: If both a slot and renderCell are defined for the same column, the slot takes precedence.
Field Name Sanitization
Since slot names must be valid HTML attribute names, field names with special characters are automatically sanitized:
Sanitization Rules:
- Invalid characters (anything not
a-z,A-Z,0-9,-,_) are replaced with underscores - Valid characters (
a-z,A-Z,0-9,-,_) remain unchanged
Examples:
| Field Name | Slot Name | Notes |
|---|---|---|
name | #cell-name | No sanitization needed ✅ |
user_id | #cell-user_id | Underscores are valid ✅ |
first-name | #cell-first-name | Hyphens are valid ✅ |
woo_ojf-AJ_3 | #cell-woo_ojf-AJ_3 | Mixed valid characters ✅ |
user.email | #cell-user_email | Dot replaced with underscore |
price$ | #cell-price_ | Dollar sign replaced |
data[0] | #cell-data_0_ | Brackets replaced |
full name | #cell-full_name | Space replaced |
<template>
<UserDatatable :columns="columns" :rows="users">
<!-- Field with dot notation -->
<template #cell-user_email="{ value }">
<a :href="`mailto:${value}`">{{ value }}</a>
</template>
<!-- Field with special characters -->
<template #cell-price_="{ value }">
${{ value }}
</template>
</UserDatatable>
</template>
Best Practice: For optimal developer experience, use field names that are already valid HTML attribute names (alphanumeric with hyphens or underscores).
Custom Headers
Use renderHeader to customize column headers with icons, tooltips, or custom styling. This is useful for adding visual cues, explanatory tooltips, or required field indicators.
Function Signature
renderHeader?: (params: NvTableRenderHeaderParams<K>) => VNode | string | number;
Function Parameters:
| Parameter | Type | Description |
|---|---|---|
headerName | string | The display name for the column header |
field | K | The field name being rendered |
Examples
Header with Tooltip:
<script setup lang="ts">
import { h } from 'vue';
import { makeColumn, NvTooltip } from '@nova-design-system/nova-vue';
const col = makeColumn<Employee>();
const columns = ref([
col({
field: 'name',
headerName: 'Full Name',
renderHeader: ({ headerName }) =>
h(
NvTooltip,
{ message: "Employee's complete legal name", placement: 'top' },
{ default: () => h('span', headerName) }
),
}),
]);
</script>
Header with Icon:
<script setup lang="ts">
import { h } from 'vue';
import { makeColumn, NvIcon } from '@nova-design-system/nova-vue';
const col = makeColumn<Employee>();
const columns = ref([
col({
field: 'salary',
headerName: 'Salary',
renderHeader: ({ headerName }) =>
h('span', { class: 'flex items-center gap-1' }, [
headerName,
h(NvIcon, { name: 'cash-banknote', size: 'sm' }),
]),
}),
]);
</script>
Header with Custom Styling (Required Field):
<script setup lang="ts">
import { h } from 'vue';
import { makeColumn } from '@nova-design-system/nova-vue';
const col = makeColumn<Employee>();
const columns = ref([
col({
field: 'status',
headerName: 'Status',
renderHeader: ({ headerName }) =>
h(
'span',
{ class: 'text-feedback-error-low font-bold' },
`${headerName} *`
),
}),
]);
</script>
Combined Example:
<script setup lang="ts">
import { h, ref, computed } from 'vue';
import {
createNvDatatable,
makeColumn,
NvTooltip,
NvIcon,
NvBadge,
type NvDatatableColumn,
} from '@nova-design-system/nova-vue';
interface Employee {
id: number;
name: string;
email: string;
department: string;
salary: number;
status: 'active' | 'inactive';
}
const EmployeeDatatable = createNvDatatable<Employee>();
const col = makeColumn<Employee>();
const columns = computed<NvDatatableColumn<Employee>[]>(() => [
col({
field: 'name',
headerName: 'Full Name',
renderHeader: ({ headerName }) =>
h(
NvTooltip,
{ message: "Employee's complete legal name", placement: 'top' },
{ default: () => h('span', headerName) }
),
}),
col({ field: 'email', headerName: 'Email Address' }),
col({ field: 'department', headerName: 'Department' }),
col({
field: 'salary',
headerName: 'Salary',
renderHeader: ({ headerName }) =>
h('span', { class: 'flex items-center gap-1' }, [
headerName,
h(NvIcon, { name: 'cash-banknote', size: 'sm' }),
]),
valueFormatter: ({ value }) => `$${value.toLocaleString()}`,
}),
col({
field: 'status',
headerName: 'Status',
renderHeader: ({ headerName }) =>
h(
'span',
{ class: 'text-feedback-error-low font-bold' },
`${headerName} *`
),
renderCell: ({ value }) =>
h(NvBadge, {
label: value,
color: value === 'active' ? 'success' : 'neutral',
}),
}),
]);
</script>
<template>
<EmployeeDatatable
mode="client"
:columns="columns"
:rows="employees"
:sorting="{}"
/>
</template>
Column Width Best Practices
When configuring column widths, follow these guidelines for optimal behavior:
⚠️ Important: Do not set width on ALL columns. Always leave at least one column without a specified width to take up the remaining space. Setting widths on every column can cause column resizing to behave incorrectly due to browser table rendering constraints.
Good Practice:
<script setup lang="ts">
const col = makeColumn<Employee>();
const columns = ref([
col({ field: 'id', width: 80 }), // Fixed narrow column
col({ field: 'name', width: 200 }), // Fixed wider column
col({ field: 'email' }), // No width - takes remaining space
col({ field: 'actions', width: 150 }), // Fixed action column
]);
</script>
Avoid:
<script setup lang="ts">
const col = makeColumn<Employee>();
const columns = ref([
col({ field: 'id', width: 80 }), // ❌ All columns have width
col({ field: 'name', width: 200 }), // ❌ Can cause resizing issues
col({ field: 'email', width: 300 }), // ❌ Browser table constraints
col({ field: 'actions', width: 150 }), // ❌ No flexible column
]);
</script>
Tips:
- Set fixed widths for columns with predictable content (IDs, actions, status badges)
- Leave content columns (names, descriptions) without fixed widths for flexibility
- Use horizontal scrolling for tables with many columns rather than cramming them into viewport
- Note: Even with fixed widths, columns may still expand if:
- Users manually resize columns (when resizable is enabled)
- Content is too wide to fit and cannot be wrapped or collapsed (browser will auto-expand to prevent overflow)
Pagination
NvDatatable supports three pagination modes to handle different data loading scenarios. The pagination behavior is determined by the top-level mode prop combined with the pagination.infinite flag.
Pagination Modes
- Client-Side Pagination: Use
mode="client"- All data is loaded at once, pagination handled in the browser - Server-Side Pagination: Use
mode="server"- Data fetched page-by-page from server with button navigation - Infinite Scroll: Use
mode="server"withpagination.infinite: true- Data loads continuously as user scrolls
Client-Side Pagination
Best for datasets under a few thousand rows where all data can be loaded at once.
Enable pagination: pass the pagination prop. Default UI: omit the #pagination slot and renderPagination to use the built-in nv-paginationtable component.
<template>
<!-- Enable pagination + use default nv-paginationtable (no #pagination slot) -->
<EmployeeDatatable
mode="client"
:columns="columns"
:rows="allData"
:pagination="{ initialPageSize: 20, pageSizeOptions: [10, 20, 50, 100] }"
/>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { createNvDatatable } from '@nova-design-system/nova-vue';
interface Employee {
id: number;
name: string;
email: string;
department: string;
}
const EmployeeDatatable = createNvDatatable<Employee>();
const columns = ref([
{ field: 'id', headerName: 'ID' },
{ field: 'name', headerName: 'Name' },
{ field: 'email', headerName: 'Email' },
{ field: 'department', headerName: 'Department' },
]);
const allData = ref<Employee[]>([
{ id: 1, name: 'John Doe', email: 'john@example.com', department: 'Engineering' },
{ id: 2, name: 'Jane Smith', email: 'jane@example.com', department: 'Marketing' },
// ... more data (100+ rows)
]);
</script>
Custom pagination UI: use the #pagination slot (or renderPagination prop):
<template>
<EmployeeDatatable
mode="client"
:columns="columns"
:rows="allData"
:pagination="{ initialPageSize: 20, pageSizeOptions: [10, 20, 50, 100] }"
>
<template #pagination="{ api }">
<div>
<NvButton @click="api.previousPage" :disabled="!api.canPreviousPage">
Previous
</NvButton>
<span>Page {{ api.pageIndex + 1 }} of {{ api.pageCount }}</span>
<NvButton @click="api.nextPage" :disabled="!api.canNextPage">
Next
</NvButton>
<select
:value="api.pageSize"
@change="(e) => api.setPageSize(Number(e.target.value))"
>
<option v-for="size in [10, 20, 50]" :key="size" :value="size">
{{ size }} rows
</option>
</select>
</div>
</template>
</EmployeeDatatable>
</template>
Key Points:
- Enable pagination: pass the
paginationprop (e.g.initialPageSize,pageSizeOptions). - Default UI: do not use
#paginationslot orrenderPagination→nv-paginationtableis used automatically. - Custom UI: use the
#paginationslot orrenderPaginationprop. - Hide UI but keep logic: use
#paginationwith a component that returns nothing, orrenderPagination: () => null(e.g. for infinite scroll). - Pass all data to the
rowsprop; no server requests needed for page changes.
Server-Side Pagination
Best for large datasets where you want to fetch data page-by-page.
⚠️ Important: In server-side mode, you must provide your own pagination UI via the #pagination slot or renderPagination prop. Unlike client-side mode, the default nv-paginationtable component is not automatically rendered in server mode. This is because server-side pagination requires custom logic to fetch data from your API when users navigate between pages.
<template>
<EmployeeDatatable
mode="server"
:columns="columns"
:rows="data"
:pagination="{
totalRowCount: totalCount,
initialPageSize: 10,
onPaginationChange: handlePaginationChange
}"
>
<template #pagination="{ api }">
<div>
<NvButton @click="api.firstPage" :disabled="!api.canPreviousPage">
First
</NvButton>
<NvButton @click="api.previousPage" :disabled="!api.canPreviousPage">
Previous
</NvButton>
<span>Page {{ api.pageIndex + 1 }} of {{ api.pageCount }}</span>
<NvButton @click="api.nextPage" :disabled="!api.canNextPage">
Next
</NvButton>
<NvButton @click="api.lastPage" :disabled="!api.canNextPage">
Last
</NvButton>
</div>
</template>
</EmployeeDatatable>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue';
import { createNvDatatable } from '@nova-design-system/nova-vue';
import { NvButton } from '@nova-design-system/nova-vue';
const EmployeeDatatable = createNvDatatable<Employee>();
const currentPage = ref(0);
const pageSize = ref(10);
const data = ref<Employee[]>([]);
const totalCount = ref(0);
// Fetch only current page data
const fetchData = async () => {
const response = await fetch(
`/api/users?page=${currentPage.value + 1}&limit=${pageSize.value}`
);
const json = await response.json();
data.value = json.data;
totalCount.value = json.pagination.total;
};
const handlePaginationChange = ({ pageIndex, pageSize: newPageSize }) => {
currentPage.value = pageIndex;
pageSize.value = newPageSize;
};
watch([currentPage, pageSize], fetchData, { immediate: true });
</script>
Key Points:
- ⚠️ Required: You must provide
#paginationslot orrenderPaginationprop to display pagination controls (no default UI in server mode) - Pass only current page data to
rowsprop (data is replaced on page change) - Provide
totalRowCountortotalPageCount - Use
onPaginationChangecallback to fetch new data - Parent component manages which page to display
Infinite Scroll
Best for continuously loading data as user scrolls, like social media feeds. Requires mode="server" with pagination.infinite: true.
<template>
<div style="max-height: 600px; overflow: auto">
<EmployeeDatatable
mode="server"
stickyHeader
:columns="columns"
:rows="loadedData"
:pagination="{
infinite: true,
hasMore,
isLoading,
loadMoreThreshold: 500,
onLoadMore: loadMore,
totalRowCount: 1000
}"
>
<template #pagination="{ api }">
<div v-if="api.isLoading">Loading more...</div>
<div v-else-if="api.hasMore">Scroll to load more</div>
<div v-else>All data loaded</div>
</template>
</EmployeeDatatable>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { createNvDatatable } from '@nova-design-system/nova-vue';
const EmployeeDatatable = createNvDatatable<Employee>();
const loadedData = ref<Employee[]>([]);
const isLoading = ref(false);
const hasMore = ref(true);
const loadMore = async () => {
isLoading.value = true;
const newData = await fetchNextPage();
loadedData.value = [...loadedData.value, ...newData]; // Append new data
hasMore.value = newData.length > 0;
isLoading.value = false;
};
onMounted(async () => {
// Load initial data
loadedData.value = await fetchInitialData();
});
</script>
Key Points:
- Pass accumulated data to
rowsprop (data is appended on load) - Wrap table in scrollable container or let it grow naturally
- Uses IntersectionObserver to detect when last row is near viewport
- Parent component maintains accumulated data array
- Set
hasMore: falsewhen all data is loaded
Pagination Configuration
The pagination behavior is determined by the top-level mode prop on the datatable.
| Property | Required | Type | Default | Description |
|---|---|---|---|---|
infinite | - | boolean | false | Enable infinite scroll (requires mode="server" on datatable) |
initialPageSize | - | number | 10 | Initial page size |
pageSizeOptions | - | number[] | [10, 25, 50, 100] | Available page size options |
| Server-side specific | ||||
totalRowCount | - | number | - | Total number of rows (for server-side pagination) |
totalPageCount | - | number | - | Total number of pages (for server-side pagination) |
onPaginationChange | - | function | - | Callback when pagination state changes |
| Infinite scroll specific | ||||
hasMore | - | boolean | - | Whether there are more items to load |
isLoading | - | boolean | - | Whether data is currently loading |
loadMoreThreshold | - | number | 500 | Distance from bottom in pixels to trigger load |
onLoadMore | - | function | - | Callback to load more data |
Pagination API
Default Pagination Behavior:
- Client mode: When
renderPaginationprop or#paginationslot is not provided, the datatable automatically renders thenv-paginationtablecomponent with full pagination controls. - Server mode: When
renderPaginationprop or#paginationslot is not provided, no pagination UI is displayed. You must provide#paginationslot orrenderPaginationprop to create your own pagination controls.
Custom Pagination:
The renderPagination prop (or #pagination slot) receives an API object with these properties and methods:
| Property | Type | Description |
|---|---|---|
| Current state | ||
pageIndex | number | Current page (zero-based) |
pageSize | number | Rows per page |
pageCount | number | Total number of pages |
rowCount | number | Total number of rows |
| Navigation methods | ||
firstPage | () => void | Navigate to first page |
previousPage | () => void | Navigate to previous page |
nextPage | () => void | Navigate to next page |
lastPage | () => void | Navigate to last page |
setPageIndex | (index: number) => void | Navigate to specific page by index |
setPageSize | (size: number) => void | Change page size |
| State queries | ||
canPreviousPage | boolean | Whether previous page is available |
canNextPage | boolean | Whether next page is available |
| Infinite scroll only | ||
isLoading | boolean | Currently loading data |
hasMore | boolean | More data available |
Sorting
NvDatatable provides comprehensive sorting capabilities with support for both client-side and server-side sorting, multi-column sorting, custom sort functions, and fine-grained control over sort behavior.
Sorting Modes
- Client-Side Sorting: All data is sorted in the browser automatically
- Server-Side Sorting: Sorting is handled by your API, table displays sorted results
Client-Side Sorting
Best for datasets that are fully loaded in the browser. The table automatically handles all sorting logic. Use mode="client" on the datatable.
<template>
<ProductDatatable
mode="client"
:columns="columns"
:rows="products"
:sorting="{}"
/>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { createNvDatatable, makeColumn } from '@nova-design-system/nova-vue';
interface Product {
id: number;
name: string;
price: number;
stock: number;
}
const ProductDatatable = createNvDatatable<Product>();
const col = makeColumn<Product>();
const columns = ref([
col({ field: 'id', headerName: 'ID', width: 80 }),
col({ field: 'name', headerName: 'Product Name' }),
col({ field: 'price', headerName: 'Price', width: 120 }),
col({ field: 'stock', headerName: 'In Stock', width: 100 }),
]);
const products = ref<Product[]>([/* ... */]);
</script>
Key Points:
- All data must be loaded in the
rowsprop - Sorting happens instantly in the browser
- No server requests needed
- Works seamlessly with client-side pagination
Initial Sort State (Uncontrolled)
When you want the table to start sorted by a specific column but still let users change the sort by clicking headers, use initialSortState. It seeds the internal sort state on first render only — unlike sortState, it does not make the component controlled.
<template>
<NvDatatable
:columns="columns"
:rows="products"
:sorting="{
initialSortState: [{ id: 'price', desc: true }],
}"
/>
</template>
When to use which:
initialSortState: your API returns unsorted data and you want a sensible default sort, but users should still be able to re-sort freely.sortState+onSortingChange: you need full control over sorting (e.g. server-side sorting, URL sync). PassingsortStatemakes the component controlled, so header clicks only take effect if you updatesortStateyourself in the callback.
If both sortState and initialSortState are provided, sortState wins.
Server-Side Sorting
Best for large datasets where sorting is performed by your backend API. Use mode="server" on the datatable.
<template>
<EmployeeDatatable
mode="server"
:columns="columns"
:rows="data"
:sorting="{
sortState: sortState,
onSortingChange: handleSortingChange,
}"
/>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import {
createNvDatatable,
makeColumn,
type NvDataTableSortingState,
} from '@nova-design-system/nova-vue';
const EmployeeDatatable = createNvDatatable<Employee>();
const col = makeColumn<Employee>();
const columns = ref([/* ... */]);
const data = ref<Employee[]>([]);
const sortState = ref<NvDataTableSortingState>([]);
const handleSortingChange = (newSortState: NvDataTableSortingState) => {
sortState.value = newSortState;
// Fetch sorted data from API
fetchData({
sortBy: newSortState[0]?.id,
sortOrder: newSortState[0]?.desc ? 'desc' : 'asc',
});
};
</script>
Key Points:
- Pass pre-sorted data to
rowsprop - Use
sortStateto control which columns are sorted - Implement
onSortingChangecallback to fetch new data - Parent component manages sort state and data fetching
SortingState Format:
type SortingState = Array<{
id: string; // Column field name
desc: boolean; // true for descending, false for ascending
}>;
// Example: sorting by price descending
const sortState = [{ id: 'price', desc: true }];
// Example: multi-sort by department asc, then salary desc
const sortState = [
{ id: 'department', desc: false },
{ id: 'salary', desc: true },
];
Column-Level Sorting Options
Each column can have individual sorting configuration:
<script setup lang="ts">
const col = makeColumn<Employee>();
const columns = ref([
col({
field: 'id',
sortable: false, // Disable sorting for this column
}),
col({
field: 'name',
sortDescFirst: true, // Start with descending when clicked
}),
col({
field: 'rank',
invertSorting: true, // Lower numbers are better (rank 1 > rank 10)
}),
col({
field: 'score',
sortUndefined: 'last', // Put null/undefined values at the end
}),
col({
field: 'customData',
sortingFn: 'alphanumeric', // Use built-in sorting function
// Or provide custom function:
// sortingFn: (rowA, rowB, columnId) => {
// return rowA.original.customData.localeCompare(rowB.original.customData);
// }
}),
]);
</script>
Multi-Column Sorting
Enable users to sort by multiple columns simultaneously:
<template>
<EmployeeDatatable
mode="client"
:columns="columns"
:rows="data"
:sorting="{
enableMultiSort: true,
maxMultiSortColCount: 3, // Limit to 3 columns (optional)
}"
/>
</template>
Usage:
- Click a header to sort by that column
- Click another header to add secondary sort (all clicks are multi-sort when enabled)
- Continue clicking to add more sort columns
- Click a sorted column again to reverse sort direction or remove it
Custom Sorting Functions
For complex sorting logic, provide a custom sortingFn:
<script setup lang="ts">
const col = makeColumn<Task>();
const columns = ref([
col({
field: 'status',
headerName: 'Status',
sortingFn: (rowA, rowB, columnId) => {
const statusOrder = { active: 1, pending: 2, inactive: 3 };
const a = statusOrder[rowA.original.status];
const b = statusOrder[rowB.original.status];
return a - b;
},
}),
]);
</script>
Built-in Sorting Functions:
You can also reference TanStack Table's built-in sorting functions by name:
'alphanumeric'- Natural alphanumeric sorting'alphanumericCaseSensitive'- Case-sensitive alphanumeric'text'- Case-insensitive text sorting'textCaseSensitive'- Case-sensitive text sorting'datetime'- Date and time sorting'basic'- Simple comparison (default)
<script setup lang="ts">
const col = makeColumn<Product>();
const columns = ref([
col({
field: 'code',
sortingFn: 'alphanumeric', // Handles "A1", "A2", "A10" correctly
}),
]);
</script>
Sorting with Value Formatters
⚠️ Important: When using valueFormatter with sorting, be aware that sorting operates on the formatted value, not the original data. This can cause unexpected sorting behavior, especially with dates and numbers.
The Problem
When you format a value for display, the sorting function sees the formatted string instead of the original data:
<script setup lang="ts">
const col = makeColumn<Employee>();
const columns = ref([
col({
field: 'employedAt',
headerName: 'Employed At',
sortingFn: 'datetime',
// ❌ WRONG: This formats the date for sorting
valueFormatter: ({ value }) => new Date(value).toLocaleDateString(),
}),
]);
</script>
Result: Dates sort alphabetically by their formatted strings instead of chronologically.
The Solution: Use renderCell
Keep the original value intact for sorting by using renderCell or scoped slots instead:
<template>
<EmployeeDatatable :columns="columns" :rows="employees">
<template #cell-employedAt="{ value }">
{{ new Date(value).toLocaleDateString() }}
</template>
</EmployeeDatatable>
</template>
<script setup lang="ts">
const col = makeColumn<Employee>();
const columns = ref([
col({
field: 'employedAt',
headerName: 'Employed At',
sortingFn: 'datetime',
// ✅ CORRECT: Sorting uses original value, formatting in slot
}),
]);
</script>
Result: Dates sort correctly while still displaying the formatted date.
Alternative: Custom Sorting Function
If you need both value transformation and custom sort logic, use a custom sortingFn:
<script setup lang="ts">
const col = makeColumn<Employee>();
const columns = ref([
col({
field: 'employedAt',
headerName: 'Employed At',
// Custom sort using original values
sortingFn: (rowA, rowB) => {
const dateA = new Date(rowA.original.employedAt).getTime();
const dateB = new Date(rowB.original.employedAt).getTime();
return dateA - dateB;
},
// Format for display
valueFormatter: ({ value }) => new Date(value).toLocaleDateString(),
}),
]);
</script>
Key Takeaway: Use scoped slots or renderCell for formatting display values when you need accurate sorting of the underlying data.
Handling Undefined Values
Control where null and undefined values appear in sorted results:
<script setup lang="ts">
const col = makeColumn<Task>();
const columns = ref([
col({
field: 'optionalField',
sortUndefined: 'last', // Options: 'first' | 'last' | false | -1 | 1
}),
]);
</script>
| Value | Behavior |
|---|---|
'first' or -1 | Undefined values appear first |
'last' or 1 | Undefined values appear last |
false | Undefined values maintain original order |
Inverted Sorting
For rankings or scenarios where lower numbers are better:
<script setup lang="ts">
const col = makeColumn<Competitor>();
const columns = ref([
col({
field: 'rank',
headerName: 'Rank',
invertSorting: true, // Rank 1 will appear before rank 10 in "ascending" sort
}),
]);
</script>
Sorting Configuration Reference
The sorting behavior is determined by the top-level mode prop on the datatable.
Global Sorting Config (sorting prop):
| Property | Required | Type | Default | Description |
|---|---|---|---|---|
enableMultiSort | - | boolean | false | Enable multi-column sorting |
enableSortingRemoval | - | boolean | true | Allow cycling through to "no sort" state |
maxMultiSortColCount | - | number | - | Maximum number of columns for multi-sort |
sortDescFirst | - | boolean | false | Start with descending sort as first toggle state |
initialSortState | - | SortingState | [] | Uncontrolled initial sort applied on first render; ignored when sortState is set |
| Server-side specific | ||||
sortState | - | SortingState | [] | Controlled sort state |
onSortingChange | - | (sorting: SortingState) => void | - | Callback when sorting changes |
Column-Level Sorting Options:
| Property | Type | Default | Description |
|---|---|---|---|
sortable | boolean | true | Enable/disable sorting for this column |
sortingFn | function | string | 'auto' | Custom sorting function or built-in function name |
sortDescFirst | boolean | false | Start with descending sort for this column |
invertSorting | boolean | false | Invert the sort order (useful for rankings) |
sortUndefined | 'first' | 'last' | false | -1 | 1 | -1 | Where to place undefined values in sort |
Horizontal Scrolling
For tables with many columns or wide content, enable horizontal scrolling by adding CSS classes:
<template>
<NvDatatable
:columns="columns"
:rows="data"
class="block overflow-x-auto"
/>
</template>
Sticky Header
Enable sticky headers to keep column headers visible when scrolling through long tables. This is especially useful for tables with many rows where you want to maintain context of what each column represents.
<template>
<NvDatatable
:columns="columns"
:rows="data"
:stickyHeader="true"
/>
</template>