Editing
To reduce per-column control binding code, use Column editors; for submitting all detail rows at once from a master form, validating virtualized off-screen rows and controlled row addition, see Detail forms. This page focuses on the useTableEdit row draft, validation and save protocol.
useTableEdit manages row drafts, validation and asynchronous saving by stable row key. It does not generate field controls; connect existing UI controls through bodyCell.
This page includes a row editing example and the complete useTableEdit API.
Editing state and validation protocol
useTableEdit aligns with the editing protocol of EditableProTable: editableKeys holds the rows currently being edited; editing ends once a save completes, and the draft is kept when validation or saving fails; the draft is discarded after onCancel completes. add() corresponds to a cached new row, which disappears when cancelled. The add button and the action column are composed by the application.
This example connects inputs and action buttons through the public methods of useTableEdit. edit.isEditing(key) accepts a stable row key and checks whether the row still has an editing draft. It remains true while a save or cancellation is pending, and when validation, saving or cancellation fails and keeps the draft open.
const edit = useTableEdit<Member>({
rowKey: 'key',
mode: 'multiple',
validate: (draft) =>
draft.name.trim() ? undefined : { fields: { name: 'Please enter a name' } },
onSave: async (draft, { key, original, isNew, signal }) => {
const saved = await api.saveMember(draft, { signal })
// Find the existing record by key, or insert when isNew; original is the edit-start snapshot.
updateDataSource(saved, { key, isNew, original })
return saved // Returning true / void also accepts the draft; returning false keeps editing.
},
})The context for validate / toValue / onSave / onCancel contains key / original / isNew / signal; toDraft has no signal. A cache addition has isNew: true and no original, so its save result may use a server-assigned key. A source addition is inserted immediately and edited as an existing row; its key cannot change.
While the user is typing, call only setDraft(); do not directly modify the source data or the return value of getDraft(). Repeated calls for the same row during a save reuse the same Promise and do not call onSave again. Cancelling or updating the draft aborts the old task, and a stale success or failure cannot close the new draft; disposing the component scope cleans up all tasks. Asynchronous application callbacks must still pass on and check signal, to keep an already cancelled request from writing back to application data.
The editing state lives in the composable, so drafts are not lost when virtual rows are unmounted off-screen. Pagination, refreshing and data replacement do not cancel drafts automatically either; the application needs to call cancel / cancelAll explicitly when leaving the page, switching datasets or deleting records.
Layout of hand-written controls
When you use useTableEdit directly and write the controls in bodyCell yourself, wrap each control in VTableEditShell. Entering edit mode then changes neither column widths nor row heights, the same behavior as layout stability for column editors.
<VTable :columns="columns" :data-source="edit.records.value" row-key="id">
<template #bodyCell="cell">
<VTableEditShell
v-if="edit.isEditing(cell.record.id) && cell.column.dataIndex === 'name'"
:cell="cell"
:original="edit.getOriginal(cell.record.id)"
:error="edit.errors.value.get(cell.record.id)?.fields?.name"
error-placement="tooltip"
>
<Input
:value="edit.getDraft(cell.record.id)?.name"
@update:value="(name) => edit.setDraft(cell.record.id, { name })"
/>
</VTableEditShell>
</template>
</VTable>When the control is a multi-line textarea, add fill to VTableEditShell: the box is stretched to the height of the cell, which suits columns whose text wraps.
- The default slot holds the control. It is stretched to the column width, so it needs no width of its own.
- The placeholder content follows the column's display rules by default (
valueType,valueEnum,columnEmptyText, and so on). If the display state usescustomRenderor other custom content, provide the same content through thedisplayslot; it receives the cell context as it was before editing. - When the table's
dataSourcecontains drafts, asedit.recordsdoes, passoriginalso the placeholder does not change while the user types. errorcomes from your code, anderrorPlacementmeans the same as inuseTableEditable.
Capability boundaries
useTableEdit already provides the row-level state, validation and save protocol; the following are still composed by the application:
- Automatic generation of query or edit forms, and dependency linkage between fields.
- Whole-table transactional submission, undo history or a concrete HTTP service.
- Excel-style arrow keys, continuous editing with Tab and cell range selection.
For field dependencies, compose your existing form solution. For a complete spreadsheet-style editing engine, consider a more full-featured option such as vxe-table.
Virtual scrolling
When a virtual row leaves the viewport, its editor unmounts but the useTableEdit draft remains keyed by the stable row key. Editing can continue when the row returns. Call cancel / cancelAll when switching datasets or deleting records.
API
The following lists every option, state and method of useTableEdit<TRecord>. TRecord is the application row type. For complete examples of controlled details and submitting all rows at once, see Detail forms.
useTableEdit options
Row drafts and saving
Asynchronous validation, saving and cancellation use context: { key, original, isNew, signal }; toDraft uses TableEditDraftContext<TRecord>, which has no signal.
| Option | Type | Default | Description |
|---|---|---|---|
rowKey | keyof TRecord | ((record: TRecord) => Key) | Required | Stable row key: a field name or a function returning string / number; the row index is not used. |
mode | 'single' | 'multiple' | 'single' | In single mode, start and add return false while a draft exists. |
clone | (record: TRecord) => TRecord | built-in clone | Clone function for the whole record. The default clones plain objects, arrays and Date; provide your own when records hold mutable class instances. |
toDraft | (record: TRecord, context: TableEditDraftContext<TRecord>) => TRecord | - | Converts the source record into a draft when editing starts. Each validateAll() run also uses it to create a temporary draft for each row without an open draft. |
toValue | (draft: TRecord, context: TableEditContext<TRecord>) => TRecord | - | Converts the draft back into a record when saving or reading the submit values. |
validate | (draft: TRecord, context: TableEditContext<TRecord>) => TableEditValidationErrors | void | Promise<TableEditValidationErrors | void> | - | (draft, context) returns { message?, fields? } synchronously or asynchronously; returning void or an empty object continues saving. |
onSave | (draft: TRecord, context: TableEditContext<TRecord>) => TRecord | void | boolean | Promise<TRecord | void | boolean> | - | Called after validation and conversion. Return a record or true / void to accept, or false to keep editing. With dataSource and onChange, saves are published automatically; otherwise update the data in application code. |
onCancel | (draft: TRecord, context: TableEditContext<TRecord>) => void | boolean | Promise<void | boolean> | - | (draft, context) cancel handler, synchronous or asynchronous. Returning false keeps the draft; a rejection records a 'cancel' error. |
onError | (error: TableEditError, key: Key) => void | - | Called when validation, saving or cancelling fails; the error is also available from errors. |
Controlled source and additions
dataSource and onChange connect the parent source records; createRecord and maxRows configure row additions.
| Option | Type | Default | Description |
|---|---|---|---|
dataSource | MaybeRefOrGetter<readonly TRecord[]> | - | Optional controlled source; pair with onChange to publish saves. When omitted, records contains only edit sessions and cached additions. |
onChange | (records: TRecord[]) => void | - | Pair with dataSource; called after a successful save or a source addition, not on each keystroke. |
createRecord | () => TRecord | - | Creates a record when add() is called without arguments. |
maxRows | number | - | Maximum number of records held on the client, including cached new rows. |
useTableEdit return value
Row state and actions
| Property or method | Type | Description |
|---|---|---|
editableKeys | ComputedRef<readonly Key[]> | Keys of the rows being edited; changed through start, add, cancel and save. |
savingKeys | ComputedRef<ReadonlySet<Key>> | Keys of the rows being saved (validation included); use them to disable editors or show a loading state. |
cancellingKeys | ComputedRef<ReadonlySet<Key>> | Keys of the rows being cancelled. |
errors | ComputedRef<ReadonlyMap<Key, TableEditError>> | Map from row key to { type, message, fields?, cause? }. |
newRecords | ComputedRef<TRecord[]> | Contains only unsaved cache additions; records already includes them. source additions require dataSource and onChange, and are inserted immediately. |
isEditing | (key: Key) => boolean | Checks the row edit session by stable key. Remains true while saving or cancelling, or after a failure retains the draft; becomes false after a successful end or reset. |
getDraft | (key: Key) => TRecord | undefined | Reads an isolated copy of the draft; apply changes through setDraft. |
start | (record: TRecord) => boolean | Creates a draft for an existing record; returns false when the row key is a duplicate. |
add | (record?: TRecord, config?: TableEditAddConfig) => boolean | Caches a new row at the end by default. Omitting record calls createRecord() if configured. Returns false if neither supplies a record, the key is a duplicate, maxRows is reached, or single mode already has a draft. Source mode requires dataSource and onChange. See TableEditAddConfig below. |
setDraft | (key: Key, patch: Partial<TRecord> | ((draft: TRecord) => TRecord)) => boolean | Merges a partial record or updates nested fields through a function; clears old errors and aborts older row tasks. Returns false for a missing or disposed edit; changing the row key throws synchronously. |
save | (key: Key) => Promise<TRecord | undefined> | Validates and saves. Returns the record and ends editing on success; returns undefined on failure or when the edit is no longer valid. |
cancel | (key: Key) => Promise<boolean> | Cancels the row; the draft and error are cleared on success. |
cancelAll | () => Promise<boolean[]> | Cancels all rows being edited. |
Detail snapshots and full validation
With dataSource, records contains source rows and drafts and can be bound to the table; pair it with onChange to publish saves. Without dataSource, it contains only edit sessions and cached additions. Submit the master form with the snapshot returned by validateAll().
| Property or method | Type | Description |
|---|---|---|
records | ComputedRef<TRecord[]> | With dataSource, contains source rows, drafts and cached additions. Without it, contains only edit sessions and cached additions. |
validating | ComputedRef<boolean> | Whether a full validation is running. |
getOriginal | (key: Key) => TRecord | undefined | Reads the snapshot of the source record taken when editing started; returns undefined for cached new rows. |
getDrafts | () => ReadonlyMap<Key, TRecord> | Reads isolated draft snapshots keyed by row key. |
getValues | () => TRecord[] | Source records plus the converted drafts; the editing state is kept and save is not called. |
validateAll | () => Promise<TableEditValidationResult<TRecord>> | Validates all records held on the client and returns the submit snapshot of that same validation, without saving. |
reset | () => void | Aborts in-flight operations and clears drafts and errors; the external source records are kept. |
TableEditAddConfig
The second argument to add(record, config) controls position and caching. When record is omitted, createRecord() supplies it.
| Field | Type | Default | Description |
|---|---|---|---|
position | 'top' | 'bottom' | 'bottom' | Position of the added row in client-held records. |
mode | 'cache' | 'source' | 'cache' | Cache mode retains a new draft until saving and removes it on cancel. Source mode immediately inserts through onChange; cancelling the edit retains the source record. |
VTableEditShell Props
| Prop | Type | Default | Description |
|---|---|---|---|
cell | TableBodyCellSlotProps<TRecord> | Required | The complete VTable bodyCell slot context. |
original | TRecord | cell.record | The record before editing, e.g. edit.getOriginal(key). The hidden layer renders it, so draft changes never resize the cell. |
layout | 'stable' | 'flow' | 'stable' | How the editing cell takes part in layout; same meaning as the layout option of useTableEditable. |
fill | boolean | false | Stretch the control to the height of the cell, for a multi-line control such as a textarea. Only applies to the stable layout. |
error | string | - | Error message of the current field. |
errorPlacement | 'inline' | 'tooltip' | 'inline' | Where the error is shown; same meaning as the errorPlacement option of useTableEditable. |
ui | Partial<Record<TableEditCellUiSlots, string>> | - | Overrides the edit slot classes for this cell. |
VTable Props
| Prop | Type | Default | Description |
|---|---|---|---|
rowKey | string | ((record: TRecord) => Key) | 'key' | Unique row identity. Selection state is recorded by row key, so it must be stable and unique. |
dataSource | TRecord[] | [] | Table data source. |
Type Declarations
TRecord is the application row type. See the Type reference for complete declarations.
View type declarations
export declare function useTableEdit<TRecord extends object>(
options: UseTableEditOptions<TRecord>,
): UseTableEditReturn<TRecord>
export interface TableEditContext<TRecord extends object> {
key: Key
/** Snapshot from start(); undefined for a cached addition until it is saved. */
original: TRecord | undefined
isNew: boolean
signal: AbortSignal
}
export type TableEditDraftContext<TRecord extends object> = Omit<
TableEditContext<TRecord>,
'signal'
>
export interface TableEditAddConfig {
position?: 'top' | 'bottom'
/** Cache until saved (default), or immediately insert into the controlled source. */
mode?: 'cache' | 'source'
}
export interface TableEditValidationErrors {
message?: string
/** Field names or business-defined nested field paths. */
fields?: Record<string, string>
}
export interface TableEditError extends TableEditValidationErrors {
type: 'validation' | 'save' | 'cancel'
message: string
cause?: unknown
}
export interface TableEditValidationResult<TRecord extends object> {
valid: boolean
/** Submitted snapshots from this validation; absent for failures or obsolete work. */
values?: TRecord[]
errors: ReadonlyMap<Key, TableEditError>
obsolete?: boolean
}
export interface UseTableEditOptions<TRecord extends object> {
/** A stable key is required; row indexes are intentionally unsupported. */
rowKey: keyof TRecord | ((record: TRecord) => Key)
/** Defaults to single. Starting another row in single mode returns false. */
mode?: 'single' | 'multiple'
/** Override when records contain mutable class instances. */
clone?: (record: TRecord) => TRecord
/** Optional controlled source. Parent updates never replace an open local draft. */
dataSource?: MaybeRefOrGetter<readonly TRecord[]>
/** Commit notifications only; draft keystrokes never write back into the source. */
onChange?: (records: TRecord[]) => void
/** Convert a record when editing starts and when validateAll() validates a row without a draft. */
toDraft?: (record: TRecord, context: TableEditDraftContext<TRecord>) => TRecord
/** Convert an editor snapshot when saving or obtaining submitted values. */
toValue?: (draft: TRecord, context: TableEditContext<TRecord>) => TRecord
/** Used by add() when no explicit record is supplied. */
createRecord?: () => TRecord
/** Maximum client-held rows, including cached additions. Finite limits round down to an integer. */
maxRows?: number
/** Return errors to keep the draft open, or void to continue saving. */
validate?: (
draft: TRecord,
context: TableEditContext<TRecord>,
) => TableEditValidationErrors | void | Promise<TableEditValidationErrors | void>
/**
* Return a canonical record, true/void to accept the submitted value, or false to keep editing.
* With dataSource and onChange, return the saved record here and update the source in onChange.
*/
onSave?: (
draft: TRecord,
context: TableEditContext<TRecord>,
) => TRecord | void | boolean | Promise<TRecord | void | boolean>
/** Returning false or rejecting keeps the draft open. Cancellation aborts a pending save first. */
onCancel?: (
draft: TRecord,
context: TableEditContext<TRecord>,
) => void | boolean | Promise<void | boolean>
onError?: (error: TableEditError, key: Key) => void
}
export interface UseTableEditReturn<TRecord extends object> {
/** Controlled source overlaid with local drafts and positioned cached additions. */
records: ComputedRef<TRecord[]>
validating: ComputedRef<boolean>
editableKeys: ComputedRef<readonly Key[]>
savingKeys: ComputedRef<ReadonlySet<Key>>
cancellingKeys: ComputedRef<ReadonlySet<Key>>
errors: ComputedRef<ReadonlyMap<Key, TableEditError>>
/** Unsaved cache-mode additions. Source-mode additions are committed through onChange. */
newRecords: ComputedRef<TRecord[]>
isEditing: (key: Key) => boolean
/** Returns an isolated copy. Use setDraft() to apply changes. */
getDraft: (key: Key) => TRecord | undefined
/** Source snapshot captured when editing began; undefined for cached additions or missing sessions. */
getOriginal: (key: Key) => TRecord | undefined
getDrafts: () => ReadonlyMap<Key, TRecord>
/** Source records plus converted draft snapshots; never calls onSave or onChange. */
getValues: () => TRecord[]
/** Validate all client-held rows, including unmounted virtual rows, without saving. */
validateAll: () => Promise<TableEditValidationResult<TRecord>>
/** Abort operations and discard drafts/errors, retaining the current controlled source. */
reset: () => void
start: (record: TRecord) => boolean
add: (record?: TRecord, config?: TableEditAddConfig) => boolean
setDraft: (key: Key, patch: Partial<TRecord> | ((draft: TRecord) => TRecord)) => boolean
/** Resolves undefined on validation/save failure, cancellation, or disposal. */
save: (key: Key) => Promise<TRecord | undefined>
cancel: (key: Key) => Promise<boolean>
cancelAll: () => Promise<boolean[]>
}export type Key = string | number