[Vuejs]-Counter not incrementing by 1 – Vue

0👍

Any data element exists outside of all methods or functions and is therefore essentially a local ‘global’ variable. So, as per your question, in fireAction() the variable counter will we initialised (set to 0) inside the method each time it is called, even though you increment it in the method. If defined within ‘data’ it can be incremented with each call of the method and will persist it’s value. You can define a variable outside of your export default and use it in method. eg:

<script>
let myVariable = 0

export default {

...

}

but using data elements is certainly my preference.

0👍

<div id="app">
  <div>{{ counter }}</div>
  <button v-on:click="increment('plus')">Increment</button>

<button v-on:click="increment('minus')">Decrement</button>
  </div>
</div>


new Vue({
el: '#app',
data: {
counter: 0
},
methods: {
increment(operator) { 
switch (operator) {
case 'minus':
if (this.counter > 0) {
this.counter--;
}
break;
case 'plus':
this.counter++;
break;
}
}
}
});

Leave a comment