我有一个简单的 Vue 应用程序,它应该在您单击“添加到集合”按钮时将数字添加到集合中 --
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);
}
}
});
为什么 watch 没有在控制台中记录任何内容?
最佳答案
使用 Set
上的 .values()
方法保存并重新设置 Set
对我有用,我不必这样做使用 $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>
关于javascript - Vue2 watch 设置不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50911030/