使用vue.set()更改属性无效



带有递增、递减、重置按钮和计数器历史值列表的简单计数器:https://codepen.io/Olivier_Tvx/pen/JjdyBMO

我希望resetCounter((清除所有以前的历史记录。我不确定什么是正确的方法。我试图将"visible"属性更改为"false"并在视图中过滤它,但没有成功。

我得到一个错误:"[Vue warn]:无法在未定义、null或基元值上设置反应属性:未定义">

我做错了什么?我需要这里的电视机吗?

JS

new Vue({
el: '#app',
data () {
return {
historics: [{
value: '',
visible: true,
}],
timer: 1000,
counter: 0,
}
},
methods: {
increaseCounter() { // Increase
clearTimeout(this.timer);
this.counter++;
this.timer = setTimeout(() => { this.pushToHistorics() }, 1000)
},
decreaseCounter() { // Decrease
clearTimeout(this.timer);
this.counter--;
this.timer = setTimeout(() => { this.pushToHistorics() }, 1000),
console.log(this.historics)
}, 
resetCounter() { // Reset
this.counter = 0;
for (historic in this.historics) {
Vue.set(this.historic, 'visible', false);
};
// for (historic in this.historics) {
// this.historic.push({visible: false});  
// };
},
pushToHistorics() {
this.historics.push({
value: this.counter,
visible: true,
})
}
},
computed: {
}
});

HTML

<div class="flex-container align-center">
<div id="app">
<button @click="increaseCounter()" class="button rounded shadow success">
Increase
</button>
<button @click="decreaseCounter()" class="button rounded shadow warning">
Decrease
</button>
<button @click="resetCounter" class="button rounded shadow alert">
Reset
</button>
<p class="text-center">
Counter: {{ counter }} <br>
</p>
<ul>
<li v-for="historic in historics.slice(0, 10)" v-if="historic.visible == true"> {{ historic.value }} - {{ historic.visible }}</li>
</ul>
</div>
</div>

您可以更新每个historicvisible属性,然后使用Vue.set()在当前数组中替换它。

resetCounter() {
this.counter = 0;
this.historics.forEach((historic, idx) => {
historic.visible = false;
Vue.set(this.historics, idx, historic);
});
}

或者,如果您想完全清除historics数组,您可以将其设置为空数组:

resetCounter() {
this.counter = 0;
this.historics = [];
}

最新更新