【问题标题】:Vue js counter increment/decrement function not working as expectedVue js 计数器递增/递减函数未按预期工作
【发布时间】:2020-06-30 09:06:22
【问题描述】:

这是一个虚拟项目:一个简单的计数器应用程序,具有增量和减量功能,可更改 2 个不同的值(“life”和“count”)并保留更改的历史记录。

在使用这两个函数时,“life”值会按预期变化。然而,“count”有不同的行为:无论使用什么函数,它的值都会增加 2。

现场示例:https://codepen.io/Olivier_Tvx/pen/JjdyBMO?editors=1111

这里有什么问题?

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},
});

【问题讨论】:

    标签: javascript vue.js counter increment


    【解决方案1】:

    有机会this.count += 1 或旧方式this.count = this.count + 1

    【讨论】:

      猜你喜欢
      • 2023-01-31
      • 1970-01-01
      • 2019-01-08
      • 1970-01-01
      • 2020-01-03
      • 2021-05-26
      • 2013-03-27
      • 2015-02-25
      • 1970-01-01
      相关资源
      最近更新 更多