NuGrid can automatically persist and restore grid state (sorting, filtering, pagination, column visibility) to localStorage.
Enable state persistence with the state prop:
<template>
<NuGrid
:data="data"
:columns="columns"
:state="{ key: 'my-grid' }"
/>
</template>
The grid will automatically save and restore:
Access state methods via the grid ref:
<script setup lang="ts">
const gridRef = useTemplateRef('grid')
// Get current state
function getState() {
const state = gridRef.value?.getState()
console.log('Current state:', state)
}
// Set state programmatically
function applyState() {
gridRef.value?.setState({
sorting: [{ id: 'price', desc: true }],
columnVisibility: { status: false },
})
}
// Clear all state
function clearState() {
gridRef.value?.setState({
sorting: [],
columnFilters: [],
columnVisibility: {},
pagination: { pageIndex: 0, pageSize: 10 },
})
}
</script>
<template>
<NuGrid
ref="grid"
:data="data"
:columns="columns"
:state="{ key: 'my-grid' }"
/>
</template>
Listen for state changes:
<script setup lang="ts">
function handleStateChange(state) {
console.log('Grid state changed:', state)
// Optionally save to your own storage
}
</script>
<template>
<NuGrid
:data="data"
:columns="columns"
:state="{ key: 'my-grid' }"
@state-changed="handleStateChange"
/>
</template>
The state object contains:
interface NuGridStateSnapshot {
sorting?: Array<{ id: string; desc: boolean }>
columnFilters?: Array<{ id: string; value: any }>
columnVisibility?: Record<string, boolean>
columnOrder?: string[]
rowSelection?: Record<string, boolean>
grouping?: string[]
pagination?: { pageIndex: number; pageSize: number }
globalFilter?: string
}
<script setup lang="ts">
import type { NuGridColumn, NuGridStateSnapshot } from '#nu-grid/types'
const gridRef = useTemplateRef('grid')
const data = ref([
{ id: 1, name: 'Laptop', category: 'Electronics', price: 1299 },
{ id: 2, name: 'Mouse', category: 'Accessories', price: 49 },
// ... more data
])
const columns: NuGridColumn<Product>[] = [
{ accessorKey: 'id', header: 'ID' },
{ accessorKey: 'name', header: 'Name' },
{ accessorKey: 'category', header: 'Category' },
{ accessorKey: 'price', header: 'Price' },
]
// Apply a preset state
function applySortedState() {
gridRef.value?.setState({
sorting: [{ id: 'price', desc: true }],
})
}
function handleStateChanged(state: NuGridStateSnapshot) {
console.log('State changed:', state)
}
</script>
<template>
<UButton @click="applySortedState">Sort by Price</UButton>
<NuGrid
ref="grid"
:data="data"
:columns="columns"
:state="{ key: 'products-grid' }"
@state-changed="handleStateChanged"
/>
</template>