javascript / expert
Snippet
Reaktive State-Snapshots für Undo/Redo
Die Implementierung von Undo/Redo-Logik erfordert Point-in-Time-Snapshots des reaktiven States. Die Verwendung von toRaw() ist hier entscheidend, um sicherzustellen, dass Sie die zugrunde liegenden Daten ohne die Proxy-Wrapper erfassen. Deep Watching ermöglicht das automatische Tracking jeder Eigenschaftsänderung, während JSON-Serialisierung (oder structuredClone) eine echte entkoppelte Kopie des Objekts für den History-Stack erstellt.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { ref, watch, toRaw } from 'vue';const state = ref({ x: 0, y: 0 });const history = ref([]);watch(state, (newVal) => {// toRaw extracts the original object to avoid tracking history itselfif (history.value.length > 20) history.value.shift();history.value.push(JSON.parse(JSON.stringify(toRaw(newVal))));}, { deep: true });function undo() {if (history.value.length > 1) {history.value.pop(); // remove currentstate.value = history.value[history.value.length - 1];}}
vue
Erklärung
1
toRaw(newVal)
Gibt die rohe, nicht-reaktive Version eines von Vue erstellten Proxy-Objekts zurück.
2
{ deep: true }
Stellt sicher, dass der Watcher auch dann auslöst, wenn verschachtelte Eigenschaften des State-Objekts geändert werden.