带有递增,递减,重置按钮和计数器历史值列表的简单计数器:https://codepen.io/Olivier_Tvx/pen/JjdyBMO
我希望resetCounter()清除所有以前的历史记录。我不确定这样做的正确方法是什么。我尝试将'visible'属性更改为'false'并在视图中对其进行过滤,但没有成功。
我得到一个错误:“ [Vue警告]:无法对未定义,空值或原始值设置未反应的属性:未定义”
我做错了什么?我需要这里的vue.set吗?
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>
答案 0 :(得分:1)
您可以为每个visible
更新historic
属性,然后使用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 = [];
}