javascript / expert
Snippet
Intercepting Reactive Array Batch Mutations via Proxy Dynamic Traps
Vue's shallowReactive optimization tracks root level reference mutations but skips deep nested wrapping. When building low-level data structures, wrapping shallowReactive arrays inside a secondary ES Proxy handler allows developers to intercept array index assignments and length mutations directly. Reflect.set guarantees target semantics, providing fine-grained telemetry control without corrupting Vue reactivity algorithms.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { shallowReactive } from 'vue';function createObservedCollection(initialItems = []) {const rawArray = [...initialItems];const reactiveHandle = shallowReactive(rawArray);return new Proxy(reactiveHandle, {set(target, prop, value, receiver) {const isIndex = typeof prop === 'string' && !isNaN(Number(prop));const result = Reflect.set(target, prop, value, receiver);if (isIndex || prop === 'length') {console.log(`Mutation detected on index/length: ${String(prop)}`);}return result;}});}
vue
Breakdown
1
const reactiveHandle = shallowReactive(rawArray);
Creates a shallow reactive proxy around the underlying array to maintain integration with Vue dependency tracking.
2
return new Proxy(reactiveHandle, {
Wraps the reactive handle in a meta-programming Proxy layer to intercept low-level object operations.
3
const isIndex = typeof prop === 'string' && !isNaN(Number(prop));
Evaluates whether the accessed property key represents a numerical array index insertion or update.
4
const result = Reflect.set(target, prop, value, receiver);
Delegates assignment execution to the native Reflect API to maintain correct prototype binding and return flags.
5
if (isIndex || prop === 'length') {
Filters logging triggers exclusively to index assignment and array resizing operational boundaries.