javascript / intermediate
Snippet
Managing Immutable Tabular Slices via toSpliced and shallowRef
Using ECMAScript's non-mutating `Array.prototype.toSpliced` in combination with Vue's `shallowRef` provides efficient immutable updates on large tabular datasets. Since `shallowRef` only tracks `.value` reassignment rather than recursively making deeply nested array elements reactive, replacing the array reference with `toSpliced` minimizes reactivity overhead while ensuring predictable change detection.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { shallowRef } from 'vue';export function useOptimisticTable(initialRows = []) {const rows = shallowRef(initialRows);const updateRowById = (id, updatedFields) => {const targetIndex = rows.value.findIndex(item => item.id === id);if (targetIndex === -1) return;const updatedItem = { ...rows.value[targetIndex], ...updatedFields };// toSpliced creates a new array without mutating the existing bufferrows.value = rows.value.toSpliced(targetIndex, 1, updatedItem);};const removeRowById = (id) => {const targetIndex = rows.value.findIndex(item => item.id === id);if (targetIndex === -1) return;rows.value = rows.value.toSpliced(targetIndex, 1);};return { rows, updateRowById, removeRowById };}
vue
Breakdown
1
const rows = shallowRef(initialRows);
Creates a shallow reactive reference that only triggers updates when its root value is reassigned.
2
const targetIndex = rows.value.findIndex(item => item.id === id);
Finds the zero-based position of the target row item using its unique identifier.
3
rows.value = rows.value.toSpliced(targetIndex, 1, updatedItem);
Returns a new copy of the array with the updated item inserted at targetIndex, assigning it to trigger reactivity.
4
rows.value = rows.value.toSpliced(targetIndex, 1);
Immutably removes the element at targetIndex and produces a new array reference.