0
0
Vueframework~5 mins

Reactive Map and Set in Vue

Choose your learning style9 modes available
Introduction

Reactive Map and Set let Vue track changes in these collections so your app updates automatically when data changes.

You want to store unique items and react to additions or removals.
You need a key-value store that updates the UI when values change.
You want to manage complex state with Map or Set and keep your UI in sync.
You are building a list of selected items that can change dynamically.
You want to react to changes in a collection without manually updating the UI.
Syntax
Vue
import { reactive } from 'vue';

const reactiveMap = reactive(new Map());
const reactiveSet = reactive(new Set());

Use reactive() to wrap a Map or Set to make it reactive.

Vue tracks changes like adding, deleting, or clearing items.

Examples
This creates a reactive Map and adds a key-value pair.
Vue
import { reactive } from 'vue';

const map = reactive(new Map());
map.set('key', 'value');
This creates a reactive Set and adds an item.
Vue
import { reactive } from 'vue';

const set = reactive(new Set());
set.add('item');
You can delete keys from Map or clear all items from Set reactively.
Vue
map.delete('key');
set.clear();
Sample Program

This Vue component shows how to use reactive Map and Set. Clicking buttons adds entries or items, and the lists update automatically.

Vue
<template>
  <div>
    <h2>Reactive Map Example</h2>
    <button @click="addEntry">Add Entry</button>
    <ul>
      <li v-for="(value, key) in reactiveMap" :key="key">
        {{ key }}: {{ value }}
      </li>
    </ul>

    <h2>Reactive Set Example</h2>
    <button @click="addItem">Add Item</button>
    <ul>
      <li v-for="item in reactiveSet" :key="item">
        {{ item }}
      </li>
    </ul>
  </div>
</template>

<script setup>
import { reactive } from 'vue';

const reactiveMap = reactive(new Map());
const reactiveSet = reactive(new Set());

let mapCount = 1;
let setCount = 1;

function addEntry() {
  reactiveMap.set(`key${mapCount}`, `value${mapCount}`);
  mapCount++;
}

function addItem() {
  reactiveSet.add(`item${setCount}`);
  setCount++;
}
</script>
OutputSuccess
Important Notes

When iterating reactive Map or Set in templates, use v-for directly on them.

Vue tracks mutations like set, add, delete, and clear.

Do not replace the whole Map or Set; mutate it to keep reactivity.

Summary

Wrap Map or Set with reactive() to make them reactive in Vue.

Mutations to reactive Map or Set update the UI automatically.

Use v-for to loop over reactive Map or Set in templates.