Does Vue support reactivity on maps and dataset sets?

The docs for Vue.js mention smart automatic change tracking for simple Javascript objects:

When you pass a simple JavaScript object to a Vue instance as its data parameter, Vue.js will pass all its properties and convert them to getter / seters using Object.defineProperty.

Since the Javascript Map and Set data types are designed to be used with the built-in get / Set methods, how can I get Vue to track calls (and therefore changes) to the internal state of Map and Set s?

+23
source share
2 answers

Vue.js does not support Map and Set reactivity (yet?).

There is a discussion in the tag and this work around (by the user "inca"):

Sets and Cards are not observed by Vue. To use them - either in v-for , or in computed properties, methods, observers, template expressions, etc. - you need to create a serializable replica of this structure and expose it to Vue. Here's a naive example that uses a simple counter to provide Vue information that Set update:

 data() { mySetChangeTracker: 1, mySet: new Set(), }, computed: { mySetAsList() { // By using `mySetChangeTracker` we tell Vue that this property depends on it, // so it gets re-evaluated whenever `mySetChangeTracker` changes return this.mySetChangeTracker && Array.from(this.mySet); }, }, methods: { add(item) { this.mySet.add(item); // Trigger Vue updates this.mySetChangeTracker += 1; } } 

This illustrates a kind of hacker, but a 100% working method of non-observable data is reactive. However, in real life, I ended up with serialized versions of Sets / Maps (for example, you probably want to store modified versions of sets / maps in localstorage and thus serialize them anyway), so there are no artificial counters / hacks It was.

+22
source share

As far as I know, Vue reactivity tracks appointments. If you are performing an assignment on your device, it should track reactivity, for example:

 methods: { add(item) { this.mySet = new Set(this.mySet.add(item)); } } 

This gives you cleaner code, but with an obvious problem: performance.

Just choose the solution according to your needs :)

0
source share

All Articles