javascript / intermediate
Snippet
Verfolgen reaktiver ES6-Sets und -Maps in Vue 3
Vue 3 unterstützt standardmäßig tiefe Reaktivität für Sammlungs-Datentypen wie Set und Map. Methodenaufrufe wie .add(), .set() und .delete() lösen das Dependency-Tracking aus und aktualisieren abhängige Computed Properties automatisch.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { reactive, computed } from 'vue';export function useTagCollection() {const activeTags = reactive(new Set(['javascript', 'vue']));const metadata = reactive(new Map([['javascript', { level: 'intermediate' }]]));const addTag = (tag, meta) => {activeTags.add(tag);if (meta) metadata.set(tag, meta);};const removeTag = (tag) => {activeTags.delete(tag);metadata.delete(tag);};const tagList = computed(() => Array.from(activeTags));return { activeTags, metadata, addTag, removeTag, tagList };}
vue
Erklärung
1
const activeTags = reactive(new Set(['javascript', 'vue']));
Initialisiert ein reaktives ES6-Set für eindeutige Elemente mit automatischer Abhängigkeitsverfolgung.
2
activeTags.add(tag);
Verändert das Set über die Standard-API und triggert reaktive Updates in abhängigen Watchern und Templates.
3
const tagList = computed(() => Array.from(activeTags));
Konvertiert das reaktive Set in ein Array für einfaches Rendering in Template-Listen.