Sometimes, we want to use JavaScript maps and sets as reactive properties in Vue.js.
In this article, we’ll look at how to use JavaScript maps and sets as reactive properties in Vue.js.
Make JavaScript Maps and Sets Reactive in Vue.js
We can use JavaScript maps and sets as reactive properties in Vue.js by reassigning them to new values.
To do that, we write:
<template>
<div id="app">
<p>{{ mapArr }}</p>
<p>{{ setArr }}</p>
</div>
</template>
<script>
export default {
name: "App",
computed: {
mapArr() {
return [...this.map.entries()];
},
setArr() {
return [...this.set.entries()];
},
},
data() {
return {
map: new Map([
["foo", 1],
["bar", 2],
]),
set: new Set([1, 2]),
};
},
mounted() {
this.map = new Map(this.map.set("baz", 3));
this.set = new Set(this.set.add(3));
},
};
</script>
We have the map
and set
reactive properties which are set to a map and a set respectively.
Then we call this.map.set
with the key and value we want to add to the map with the this.map.set
method.
And we pass in the returned set into the Map
constructor and assign it to the this.map
reactive property to update it.
Next, we call this.set.add
to add a new entry to this.set
.
And then we pass the returned set into the Set
constructor and assign it to this.set
to update it.
We converted the sets and maps to arrays in the setArr
and mapArr
computed properties respectively and then render them on the template.
And we that we get:
[ [ "foo", 1 ], [ "bar", 2 ], [ "baz", 3 ] ]
as the value of mapArr
and:
[ [ 1, 1 ], [ 2, 2 ], [ 3, 3 ] ]
as the value of setArr
.
Conclusion
We can use JavaScript maps and sets as reactive properties in Vue.js by reassigning them to new values.