I have a simple Vue app that is supposed to add a number to a Set when you click the "Add to Set" button --
https://codepen.io/jerryji/pen/mKqNvm?editors=1011
<div id="app">
<input type="number" placeholder="enter a number" v-model="n">
<button type="button" @click.prevent="addToSet()">Add to Set</button>
</div>
new Vue({
el: "#app",
data: {
n: null,
nSet: new Set()
},
methods: {
addToSet: function() {
this.nSet.add(this.n);
console.log(this.n + ' added to Set');
}
},
watch: {
nSet: function (newVal, oldVal) {
console.log(newVal);
}
}
});
Why is nothing logged in the console by the watch?
It's because Vue doesn't support Set, Map, WeakSet and WeakMap. And it's because browsers didn't support these structures well. Especially WeakMap. But... They decided to support these structures. Maybe in version 3 - when they decide to drop support for older browsers. So, for now use an object, add properties with
Vue.$set()
and watch for changes withdeep: true
.Saving and re
Set
ting the Set using the.values()
method onSet
worked for me and i didn't have to use$forceUpdate
Using
$forceUpdate
might be the more sensible way to go though. In some use cases in the past i have found forcing components to update to be problematic.Vue adds special handling for Arrays, but not for Sets. As a result, Vue doesn't automatically detect changes to Set membership. You can force an update, though