Issue with Vue js counter increment and decrement function not performing as anticipated

Here we have an example of a dummy project: An app with a counter feature that allows for both increment and decrement functions which change two different values ("life" and "count") and also keeps a record of the changes.

The "life" value behaves as expected when using either of the functions. However, the "count" value has a peculiar behavior: it always increases by 2 regardless of which function is used.

For a live demonstration, you can check out this link: https://codepen.io/Olivier_Tvx/pen/JjdyBMO?editors=1111

Can you spot what might be going wrong with this implementation?

JavaScript Code:

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

Answer №1

Consider using this.count += 1 instead of the more traditional this.count = this.count + 1

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What advantages does mapState offer compared to mapGetters when working with Vuex?

While evaluating the company code, I came across a Vue component with computed properties structured like this: computed: { ...mapState('settings', { site: state => state.general.site }), ...mapGetters('settings', ...

Managing individual HTTP responses within Angular 6

I currently have 15 HTTP requests being sent to the API individually. Instead of waiting for all requests to finish processing (especially one that can take a few minutes), I want to handle responses as they come in. On the service side: findOneByOne ...

Moving logic from the controller to the service in Node.js Express to streamline the code

Recently, I have been working on a project that involves fetching data from an API. To streamline the code and improve organization, I am looking to offload the program logic to a service, keeping my controller neat and tidy. I have been reading up on Asy ...

Using $watchGroup to monitor changes in an array and automatically updating it

Issue: I am facing a challenge where I want to pass an array of variables into $watchGroup and iterate through the array to update the values of each element. However, the current approach I am using does not seem to be effective: $scope.secondsElapsed = ...

How can React hook state be efficiently utilized in a debounced callback?

function Foo() { const [state, setState] = useState(0); const cb = useCallback(debounce(() => { console.log(state); }, 1000), []); return ...; } In the code snippet above, there is a potential issue where the state variable may become outda ...

What is the Best Method to Retrieve the Desired Data from a YQL Query using a Callback Function?

I successfully implemented a callback function that retrieves titles related to a user-submitted string in a text input box. However, I am struggling with how to extract only the titles from the returned callback function after submitting a search term. C ...

What are the reasons that execCommand does not function correctly when attempting to justify text?

Why isn't justify with execCommand working properly? Take a look at the code below: $('#JustifyLeft').click(function(){ document.execCommand("JustifyLeft", false, ""); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2 ...

Exploring Pg-promise: the power of chaining conditional queries

I am currently working on figuring out the best approach for chaining conditional queries in my project. Let me break down my scenario using some pseudo-code: We first need to check if an item exists; if it doesn't: respond with a status of 40 ...

Drag items from one list to another within the same container using vue-smooth-dnd

I'm currently using the vue-smooth-dnd component and I'm trying to figure out how to drop an element into a list within the same list. The official documentation only provides limited guidance, found at . However, I need something more specific ...

Exploring ways to enhance the appearance of a Sidebar Widget Navigation using JQuery

When creating navigational items with submenus, such as 'Primary Fees', I added an arrow for visual indication. To enhance user experience, I included an animation that rotates the arrow and highlights the Main Menu item in red upon hovering. Thi ...

The window fails to retain the scroll position when overflow is enabled

Whenever I click on a specific div, I use jQuery to dynamically apply overflow: hidden to the html and body. $(".mydiv").on("click", function() { $("html, body").css("overflow", "hidden"); }); However, this action causes the window to scroll to the to ...

Is there a way for me to create a link that is specifically for printing on 3D printers, rather than a link for downloading the

I have a project with a company that sells 3D printable models (.STL) online. They want to add specific models to their digital inventory without allowing direct downloads. Instead, once a customer purchases a model, they should be able to immediately pr ...

Converting Strings to Booleans in Vue: A Dilemma

Within my Vue HTML code, I have the following: <v-textarea auto-grow="true"></v-textarea> The functionality works as intended, with the textarea expanding automatically. However, it does trigger an error message: [Vue warn]: Invalid ...

C#: How to Automatically Choose Dropdown Options Using Marionette Driver

Currently, I am utilizing Selenium Webdriver alongside C# bindings and transitioning from the outdated FirefoxDriver (pre-FF 47) to the newer Marionette driver (FF47 and above). The switch has been successful after encountering some initial challenges that ...

When a string begins with the "<" character, jQuery regex is unable to find a match

I am attempting to check if a string starts with the "<" character, but I am running into issues. The expression works perfectly fine on regex101.com, however, it fails when used in my personal files. When I input a backslash everything works as expect ...

Vue component always renders a new line

Whenever I include a <component> tag in my main application, it always renders on a new line. Is there a way to make it inline? I am trying to achieve something like this: <p>This is a component :<component></component></p> & ...

What is the best way to make an image expand when clicked, align it in the center of the webpage, and have it return to its original position with just one more click by utilizing

Currently, this is the code I am working with. The JavaScript functionality is working well, however, there seems to be an issue where the image does not return to its original size on a second click. Additionally, I am having trouble getting the CSS to ce ...

Is there a way to incorporate Vue script in Laravel without utilizing Vue templates?

I have a question that may seem simple, but I'm curious about the best way to use vue script on pages individually without declaring it globally. For example, I have multiple pages in Laravel Blade such as the home page, category page, and product pag ...

Tips for preventing a React component from re-fetching data when navigating back using the browser button

In my React app using Next.js and the Next Link for routing, I have two pages set up: /product-list?year=2020 and /product-list/details?year=2020&month=4 Within the pages/product-list.js file, I am utilizing React router to grab the query parameter ye ...

Unsubscribe from the Event Listener in Node.js

In light of this inquiry (linked here), can the Listener be eliminated from within the callback function? To illustrate: let callback = function(stream) { if(condition) performAction(); else server.removeListener('connection', cal ...