Use with Vue
The <Grid> component passes your options to the grid, turns grid events into emit calls and cleans up when it unmounts. Sorting, selection, editing and saving all live in core. This guide covers only what is specific to Vue. The parts shared by all three frameworks are in Framework guide.
Each example linked below runs on the real @maxgrid/vue. Every one is a single .vue file you can copy as it is. The full list is in the Vue integration examples.
Install
Vue 3.4 or later is required, and vue is a peer dependency.
pnpm add @maxgrid/vue @maxgrid/themes// main.ts: import the theme CSS once, at the app entry.
import '@maxgrid/themes/grid.css';Give <Grid> its own height. A height on an outer element alone lets the grid grow, which turns virtual scrolling off and renders every row.
<script setup lang="ts">
import { Grid, type GridOptions } from '@maxgrid/vue';
import { shallowRef } from 'vue';
interface Employee {
id: number;
name: string;
department: string;
}
const options = shallowRef<GridOptions<Employee>>({
columns: [
{ id: 'name', title: 'Name' },
{ id: 'department', title: 'Department' },
],
rows: [
{ id: 1, name: 'Liam Carter', department: 'Engineering' },
{ id: 2, name: 'Emma Wilson', department: 'Design' },
],
rowKey: 'id',
});
</script>
<template>
<Grid style="height: 300px" :options="options" />
</template>What the Grid component accepts
| Kind | Name | Notes |
|---|---|---|
| props | options | GridOptions<TRow>. Required. |
| props | selectedKeys, sortModel, filterModel | Selection, sort and filter state. Bind with v-model. Without them the grid keeps its own state |
| emits | Every core event name (@sortChanged …) | Names match the table in Events |
| emits | update:selectedKeys, update:sortModel … | The events v-model uses |
| expose | getApi() | Read it from a template ref. Returns null when there is no grid |
A class or style on <Grid> lands on its outer <div>. Set the height here, either inline or with a CSS class.
Keep options in a shallowRef
Before passing options to the grid, the wrapper applies toRaw to every top-level value. Options wrapped in ref or reactive work, but shallowRef is the better choice.
| How you hold it | Row objects | options.rows.push(...) |
|---|---|---|
shallowRef(options) | Not proxies | The grid does not notice |
ref(options), reactive | The grid gets raw objects. Your own reads return proxies | The grid does not notice |
data() + markRaw(rows) | An array wrapped in markRaw never becomes a proxy | The grid does not notice |
shallowRef helps in two ways. With tens of thousands of rows, Vue does not build a proxy per row. And a row you read out of a ref and hand to api.updateRows or api.addRows never carries a proxy into core.
To change data, assign a new array or a new object. Editing an array in place (push, splice, row.name = ...) is invisible to the grid.
// Add a row: replace the array.
options.value = { ...options.value, rows: [newRow, ...options.value.rows] };
// Change one row: pass a new object for just that row.
api.updateRows([{ ...row, name: 'New name' }]);Passing the same options object again does nothing. Passing a new object makes core compare it property by property and apply only what changed. That makes a computed options object fine.
Examples: Connect the grid to a Pinia store, Handle 100,000 rows without proxies
Load rows from a server
Set loading: true in the options to show the loading state. Requests can overlap, so number them and drop stale answers.
let latest = 0;
async function load() {
const ticket = ++latest;
options.value = { ...options.value, loading: true };
const rows = await fetchRows();
if (ticket !== latest) return; // a newer request exists
options.value = { ...options.value, rows, loading: false };
}Example: Load rows from a server with a loading state
Bind selection, sort and filter with v-model
You can bind selectedKeys, sortModel and filterModel with v-model.
<script setup lang="ts">
import { ref } from 'vue';
import type { FilterModel, RowKey, SortItem } from '@maxgrid/vue';
const selected = ref<RowKey[]>([]);
const sort = ref<SortItem[]>([]);
const filter = ref<FilterModel | null>(null);
</script>
<template>
<Grid
:options="options"
v-model:selectedKeys="selected"
v-model:sortModel="sort"
v-model:filterModel="filter"
/>
</template>The grid owns the state. When your value changes, the wrapper compares it deeply with the grid's current value and calls setSelectedKeys, setSortModel or setFilterModel only if they differ. Changes made in the grid come back through update:*. The two sides never push each other in a loop.
- Without the prop, the grid is uncontrolled. It keeps the state and you read it from events.
- The initial value is applied once, right after the grid is created.
- A row key that does not exist in
selectedKeysmakes core throwinvalid-option, and the selection stays as it was.
Examples: Bind selection, sort and filter with v-model, Keep filter and sort in the route query
Keep state in the route query
To make the query string the source of truth, connect the prop and the update:* event separately instead of using v-model. Build a FilterModel and a SortItem[] from the query, and write grid changes back with router.replace.
const route = useRoute();
const router = useRouter();
const sortModel = computed<SortItem[]>(() => {
const [columnId, direction] = String(route.query.sort ?? '').split(':');
return columnId && (direction === 'asc' || direction === 'desc') ? [{ columnId, direction }] : [];
});
const onSort = (model: SortItem[]) => {
const first = model[0];
router.replace({
query: { ...route.query, sort: first ? `${first.columnId}:${first.direction}` : undefined },
});
};<Grid :options="options" :sortModel="sortModel" @update:sortModel="onSort" />The grid is not touched when the value is the same, so the value coming back from replace does not loop. Use push instead of replace if you want each change in the history.
Listen to events
The core event names are the emit names.
<Grid
:options="options"
@cellClicked="({ rowKey, columnId }) => open(rowKey)"
@selectionChanged="({ selectedKeys }) => (count = selectedKeys.length)"
@editCommitted="({ columnId, oldValue, newValue }) => log(columnId, oldValue, newValue)"
/>In a render function or h(Grid, ...), pass them as props with an on prefix, such as onCellClicked. The list of names comes from one place in core, so the wrapper does not change when core adds an event.
@scrolled fires on every scroll. Keep its handler light.
Example: Edit the selected row in a form
Call GridApi from a template ref
To call methods directly, use a template ref. It holds an object with getApi().
<script setup lang="ts">
import { Grid, type GridInstance } from '@maxgrid/vue';
import { ref } from 'vue';
const grid = ref<GridInstance<Employee> | null>(null);
const ready = ref(false);
const jump = () => grid.value?.getApi()?.scrollToRow(500);
</script>
<template>
<button :disabled="!ready" @click="jump">Go to row 500</button>
<Grid ref="grid" :options="options" @ready="ready = true" />
</template>getApi() returns null before mount and after unmount. Do anything that must run once right after creation in @ready. Setting ready there, as above, keeps the button off until the grid exists.
In the Options API, use this.$refs.grid.getApi().
Examples: Call GridApi from a template ref, Use the grid with the Options API
Options API
data() makes its return value deeply reactive. Wrap the rows array in markRaw so it never becomes a proxy. To change rows, assign a new array, just like in the Composition API.
data() {
return {
options: { columns, rows: markRaw(rows), rowKey: 'id' } as GridOptions<Employee>,
};
},
methods: {
add(row: Employee) {
this.options = { ...this.options, rows: markRaw([row, ...this.options.rows]) };
},
},Render cells with Vue components
Wrap a component with vueCell for cellRenderer, and with vueEditor for cellEditor. The props a component receives and the editor rules are in Cells from components. This section lists only what matters in Vue.
import { vueCell, vueEditor } from '@maxgrid/vue';
const columns = [
{ id: 'status', title: 'Status', cellRenderer: vueCell(StatusBadge) },
{
id: 'department',
title: 'Department',
editable: true,
cellEditor: vueEditor(DepartmentEditor),
},
{ id: 'open', title: '', cellRenderer: vueCell(OpenButton, { props: { onOpen } }) },
];- The app context is shared. A cell component can use global components, plugins (i18n, router), app-level
provide, and values provided by any ancestor of<Grid>throughinject. - Slots are not supported. There is no slot renderer such as
<template #cell-name>. Build cells as components. - Cell components are reactive. When an injected
refor a store value changes, the cell repaints by itself. - A new row changes only the props. Scrolling reuses the same component for another row. If a component holds state, use
vueCell(Comp, { keyed: true })to create a fresh one per row. - An editor component receives the
modelValueanderrorprops and emitsupdate:modelValue,commitandcancel. The grid handles Enter, Esc and Tab. - If a cell component throws, only that cell shows an error and the grid keeps working.
Pass component cells through options.columns only. Columns given straight to api.setColumns() skip <Grid> and have no app context.
Examples: Render cells with Vue components, Edit cells with a Vue component, Use provide and inject in cells
Build a save button
useChangeStatus() returns refs for the added, edited and removed counts, the saving flag and the rows that failed. Bind its listeners to <Grid> with v-bind, or the values never update.
<script setup lang="ts">
import { Grid, useChangeStatus, type GridInstance } from '@maxgrid/vue';
import { ref } from 'vue';
const grid = ref<GridInstance<Employee> | null>(null);
const { count, saving, failed, listeners } = useChangeStatus();
const save = () => grid.value?.getApi()?.save();
</script>
<template>
<button :disabled="!count || saving" @click="save">{{ saving ? 'Saving…' : 'Save' }}</button>
<Grid ref="grid" :options="options" v-bind="listeners" />
</template>Put the save rules (saveMode, saveHandler) in the options. Core does the saving. See Save changes in a batch for details.
Example: Wire a save button to the change state
Theme and density
The theme is the data-mxg-theme attribute on the grid or any ancestor. Put it on a wrapper and only that grid changes. Density is the density option.
<div :data-mxg-theme="dark ? 'dark' : 'light'">
<Grid style="height: 300px" :options="options" />
</div>To switch the whole page, set the attribute on document.documentElement. The CSS variables you can override are listed in Theme.
Example: Switch theme and density
Nuxt and server rendering
On the server the component renders an empty <div> and creates no grid. The grid appears after mount in the browser, so the server and client HTML have the same structure and hydration does not mismatch. Importing the package does not touch window or document.
That means server rendering works without <ClientOnly>. Wrapping the grid still helps in two cases.
- You want a placeholder instead of an empty area in the server HTML. Put an element of the same height in the
#fallbackslot and the page does not shift. - The code that builds
optionsor the cell components readswindoworlocalStorage.
<template>
<ClientOnly>
<Grid style="height: 400px" :options="options" />
<template #fallback>
<div style="height: 400px" aria-busy="true" />
</template>
</ClientOnly>
</template>Add the theme CSS in css of nuxt.config.ts.
export default defineNuxtConfig({
css: ['@maxgrid/themes/grid.css'],
});What was verified (2026-11-28)
Nuxt 4.7.0, Vue 3.5.46 and the published @maxgrid/vue 1.7.2, with nuxt build and the Node server, checked in Chromium (nuxt dev was checked with 1.7.0). The grid and the gantt split view both draw without hydration warnings.
- The server HTML holds only the empty
<div>where the grid goes, and the grid is drawn with no hydration warning. The theme fromcssbecomes a stylesheet link in<head>, so there is no flash. One grid remains after 2,000-row virtual scrolling, route changes and HMR. - Call
createGanttandattachGridafteronMountedin a component inside<ClientOnly>. Using a.client.vuefile name and<ClientOnly>together leaves the template ref empty inonMounted, so use only one of them. downloadXlsxworks in a click handler.- Opened on a non-localhost host without a license key, the evaluation strip appears under the grid and the chart and an evaluation-mode notice appears in the console. Keep the key in
runtimeConfig.publicand passlicenseKey: useRuntimeConfig().public.mxgKey; thenNUXT_PUBLIC_MXG_KEY=…can be set when the server starts (not at build time). A valid key was not tried (a wrong key gives a malformed-key notice). vue-router5.5.2 returns 500 on every page on the server (__VUE_OPTIONS_API__ is not defined). This is a problem in a third-party package, not in MaxGrid. The version installed now (5.5.3) does not have it; if 5.5.2 gets installed, pinvue-routerto 5.5.1 or newer (not 5.5.2) withoverrides.
TypeScript generics
Pass the row type to the options and to refs.
| Where | Type |
|---|---|
| Options | GridOptions<Employee> |
| Template ref | GridInstance<Employee> |
| Component cells in columns | vueCell<Employee>(Comp), vueEditor<Employee>(Comp) |
| Props in a render function | GridProps<Employee> |
Grid itself is not a generic component, so the row in an event payload arrives as object. When you need the row type, read the typed row with getApi()?.getRowByKey(rowKey), or narrow it in the handler.
const grid = ref<GridInstance<Employee> | null>(null);
function open(rowKey: RowKey) {
const row = grid.value?.getApi()?.getRowByKey(rowKey); // Employee | undefined
}A reusable component that wraps the grid takes the row type through the generic attribute.
<script setup lang="ts" generic="TRow extends object">
import { Grid, type GridOptions } from '@maxgrid/vue';
defineProps<{ options: GridOptions<TRow> }>();
const emit = defineEmits<{ rowClicked: [row: TRow] }>();
</script>
<template>
<Grid :options="options" @rowClicked="({ row }) => emit('rowClicked', row as TRow)" />
</template>@maxgrid/vue re-exports core types such as GridOptions, ColumnDef and GridApi. You do not need to install @maxgrid/core yourself.
Common mistakes
- Pushing to a rows array held in a
ref. The grid cannot tell that anything changed. Assign a new array. - Building new
optionson every render.:options="{ columns, rows }"gives the grid a new object each time the parent renders. The result is correct but wasteful. Keep the columns outside the component or in acomputed. - Binding a form straight to a row object with
v-model. Each keystroke edits the grid's own data and skips change tracking. Bind a copy and callapi.updateRowswhen the user applies it. - Using
getApi()right after mount. It isnulluntil the grid exists. Wait for@ready. - Forgetting the
listenersofuseChangeStatus. Withoutv-bind="listeners",countstays 0. - Passing component cells to
api.setColumns(). They turn into error cells. Changeoptionsinstead. - Setting the height on an outer
divonly. The grid does not receive it, grows without limit and renders every row. Give the height to the grid itself, as in<Grid style="height: 300px">. - Expecting
@errorto report a failure in the very first render. That happens before the wrapper subscribes, so the error reachesconsole.erroronly. Errors after mount do arrive through@error.
All examples
| What you want to do | Example |
|---|---|
| Keep state in step with refs | v-model |
| Load from a server | Loading state |
| Connect a store | Pinia store |
| Edit in a form | Edit the selected row |
| Render cells as components | Vue component cells |
| Edit cells with components | Vue component editor |
| Use provide and inject | inject in cells |
| Sync with the route query | Query sync |
| Large data | 100,000 rows |
| Save button | Change state |
| Switch the theme | Theme and density |
| Call GridApi | Template ref |
| Options API | Use with the Options API |