javascript / expert
Snippet
Optimization with ShallowRef and TriggerRef
For massive data structures, deep reactivity is expensive. ShallowRef only tracks the .value property. TriggerRef allows manual UI updates after internal mutations, providing a massive performance boost.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
import { shallowRef, triggerRef } from 'vue';const largeState = shallowRef({ data: new Array(1000).fill(0) });function updateElement(index, value) {// Mutation doesn't trigger reactivity because it's shallowlargeState.value.data[index] = value;// Manually trigger updates for the shallow referencetriggerRef(largeState);}
vue
Breakdown
1
const largeState = shallowRef(...);
Creates a ref that only triggers updates when the entire object reference is replaced.
2
largeState.value.data[index] = value;
Mutates the internal data without triggering Vue's expensive recursive proxy system.
3
triggerRef(largeState);
Explicitly tells Vue to check the shallow ref for changes and update the DOM.