Vue2 手表集不工作



>我有一个简单的 Vue 应用程序,当你点击"添加到集合"按钮时,它应该会向 Set 添加一个数字——

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);
}
}
});

为什么手表没有在控制台中记录任何内容?

Set使用.values()方法保存并重新SetSet 对我有用,我不必使用$forceUpdate

不过,使用$forceUpdate可能是更明智的方法。在过去的一些用例中,我发现强制组件更新是有问题的。

new Vue({
el: "#app",
data: {
n: null,
nSet: new Set()
},
methods: {
addToSet: function() {
let set = this.nSet;
let newSet = set.add(this.n)
this.nSet = new Set(newSet.values())
}
},
watch: {
nSet: function (newVal, oldVal) {
console.log('newVal', ...newVal);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="app">
<input type="number" placeholder="enter a number" v-model="n">
<button type="button" @click.prevent="addToSet()">Add to Set</button>
<p>n = {{ n }}</p>
</div>

Vue 为 Array 添加了特殊处理,但没有为 Set 添加特殊处理。因此,Vue 不会自动检测对设置成员资格的更改。不过,您可以强制更新

this.nSet.add(this.n);
this.$forceUpdate();

这是因为 Vue 不支持 Set、Map、WeakSet 和 WeakMap。这是因为浏览器不能很好地支持这些结构。尤其是弱地图。但。。。他们决定支持这些结构。也许在版本 3 中 - 当他们决定放弃对旧浏览器的支持时。因此,现在使用对象,使用Vue.$set()添加属性,并使用deep: true观察更改。

最新更新