javascript / intermediate
Snippet
Tracking Reactive Item Selection Sets with Native JavaScript Set
Using JavaScript's built-in Set data structure ensures unique ID tracking and O(1) lookup performance for selection states. Reassigning a new Set instance when mutating entries maintains predictable reactivity triggering across Vue components.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { ref } from 'vue';export function useSelectionSet() {const selectedIds = ref(new Set());const toggleSelection = (id) => {const next = new Set(selectedIds.value);if (next.has(id)) {next.delete(id);} else {next.add(id);}selectedIds.value = next;};const isSelected = (id) => selectedIds.value.has(id);const clearSelection = () => { selectedIds.value = new Set(); };return { selectedIds, toggleSelection, isSelected, clearSelection };}
vue
Breakdown
1
const selectedIds = ref(new Set());
Wraps a standard ES6 Set collection within a Vue reactive reference.
2
const next = new Set(selectedIds.value);
Creates a shallow clone of the existing Set to perform immutable updates.
3
if (next.has(id)) { next.delete(id); } else { next.add(id); }
Performs fast membership check and conditionally adds or removes the identifier from the collection.
4
selectedIds.value = next;
Reassigns the reference value to cleanly trigger reactivity notifications for dependent computed properties and watchers.