javascript / intermediate
Snippet
Tracking Reactive ES6 Sets and Maps in Vue 3
Vue 3 natively supports deep reactivity on collection data types such as Set and Map. Method calls like .add(), .set(), and .delete() trigger dependency tracking and re-evaluate dependent computed properties automatically.
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
Breakdown
1
const activeTags = reactive(new Set(['javascript', 'vue']));
Initializes a reactive ES6 Set ensuring unique items with automatic dependency tracking.
2
activeTags.add(tag);
Modifies the Set via standard API, triggering reactive updates in observing watchers and templates.
3
const tagList = computed(() => Array.from(activeTags));
Transforms the reactive Set collection into an Array for straightforward template list rendering.