简体   繁体   中英

Vue js counter increment/decrement function not working as expected

Here is a dummy project: A simple counter app with increment and decrement function that change 2 different values ("life" and "count") and keep historic of changes.

"life" value change as expected while using both of the functions. However "count" has a different behavior: it's value increase by 2 whatever the function used.

Live example: https://codepen.io/Olivier_Tvx/pen/JjdyBMO?editors=1111

What's wrong here ?

JS

   let player = {
    data: function () {
    return {
    life: '20',
    poison: '0',
    timer: '1500',
    count: '0',
    historics: [{
        value: '',
        }],
    }
  },
  methods: {
    increaseLife: function() { 
      clearTimeout(this.timer);
      clearTimeout(this.count);
      this.life++;
      this.count++;
      this.timer = setTimeout(() => { this.pushToHistorics() }, 1500);
      this.count = setTimeout(() => { this.countClear() }, 1000)
    },
    decreaseLife: function() { 
      clearTimeout(this.timer);
      clearTimeout(this.count);
      this.count--;
      this.life--;
      this.timer = setTimeout(() => {this.pushToHistorics() }, 1500);
      this.count = setTimeout(() => { this.countClear() }, 1000)
    }, 
    countClear: function() {
      this.count = 0;
    },
    reset: function() {
    this.life = 20;
    this.poison = 0;
    this.historics = [];
    this.count = 0;
    },
   pushToHistorics: function() {
    this.historics.push({
      value: this.life,
    })
    },
  },

  template: `
    <div class="global">
      <div class="count"><span v-show="count > 0">counter : {{ count }}</span></div>
      <div>PV : {{ life }} </div>
      <span>Poison : {{ poison }} </span>
      <div class="containterBtn">
      <button @click="increaseLife(); increaseCount()">+</button>
      <button @click="decreaseLife()">-</button>      
      <button @click="reset()">reset</button>
      </div>
      <div class="historics" v-for="historic in historics.slice(0, 10)">
         <div class="historic">{{ historic.value }}</div>
      </div>

    </div>
  `
};

let vm = new Vue({
  el: '#app',
  components: {player},
});

this.count += 1或旧方式this.count = this.count + 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM