Reputation: 361
Simple counter with increment, decrement, reset buttons and a list of the historic values of the counter : https://codepen.io/Olivier_Tvx/pen/JjdyBMO
I want resetCounter() to clear all the previous historics. I am not sure what is the proper way to do it. I try to change the 'visible" property to 'false' and filter it in the view, without success.
I get an error : "[Vue warn]: Cannot set reactive property on undefined, null, or primitive value: undefined"
What I am doing wrong? Do I need vue.set here?
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>
Upvotes: 1
Views: 263
Reputation: 606
You can update the visible
property for each historic
then use Vue.set()
to replace it in the current array.
resetCounter() {
this.counter = 0;
this.historics.forEach((historic, idx) => {
historic.visible = false;
Vue.set(this.historics, idx, historic);
});
}
Or if you want to clear the historics
array altogether, you can just set it to an empty array:
resetCounter() {
this.counter = 0;
this.historics = [];
}
Upvotes: 1