Vue2 Watch Set Not Working
Solution 1:
Saving and re Set
ting the Set using the .values()
method on Set
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.
newVue({
el: "#app",
data: {
n: null,
nSet: newSet()
},
methods: {
addToSet: function() {
let set = this.nSet;
let newSet = set.add(this.n)
this.nSet = newSet(newSet.values())
}
},
watch: {
nSet: function (newVal, oldVal) {
console.log('newVal', ...newVal);
}
}
});
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script><divid="app"><inputtype="number"placeholder="enter a number"v-model="n"><buttontype="button" @click.prevent="addToSet()">Add to Set</button><p>n = {{ n }}</p></div>
Solution 2:
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
this.nSet.add(this.n);
this.$forceUpdate();
Solution 3:
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 with deep: true
.
Post a Comment for "Vue2 Watch Set Not Working"