Issue involving if statements and Vue.js causing counter to reset

I am currently working on a simple code snippet that updates a counter each time a specific button is clicked. The counter restarts once it reaches 3 and the number is displayed on each button. Everything seems to be functioning correctly, but I have come across a strange issue - if the first button does not start at 0, clicking any other button will reset the first button's value back to 0. Could this suggest that the buttons are somehow connected?

new Vue({
  el: "#app",
  data: {
    one: 0,
    two: 0,
    three: 0
  },
  methods: {
    chooseOne: function(x, y) {
      if ((x == 1) && (this.one < 3)) {
        this.one++;
      } else {
        this.one = 0
      }
      if (x == 2) {
        if ((x == 2) && (this.two < 3)) {
          this.two++;
        } else {
          this.two = 0
        }
      }
      if (x == 3) {
        if ((x == 3) && (this.three < 3)) {
          this.three++
        } else {
          this.three = 0
        }
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button @click="chooseOne(1,one)">
      {{ one }}
     </button>
  <button @click="chooseOne(2,two)">
      {{ two }} 
     </button>
  <button @click="chooseOne(3,three)">
      {{ three }}
     </button>
</div>

Answer №1

Your if-else statement lacks consistency in handling all values of x. It checks for nested conditions when x is 2 and 3, but not when x is 1. Specifically, when x = 2, the condition is evaluated as false.

if ((x == 1) && (this.one < 3))

Therefore, the statement this.one = 0 is executed whenever the second or third button is clicked.

To rectify this issue, you should include a similar check for x equals to 1:

  if (x == 1) {
    if (this.one < 3) {
      this.one++;
    } else {
      this.one = 0
    }
  }

An alternative approach to streamline your code is by passing the property name as a parameter, like so:

new Vue({
  el: "#app",
  data: {
    one: 0,
    two: 0,
    three: 0
  },
  methods: {
    chooseOne: function(prop) {
      if (this[prop] < 3) {
        this[prop]++
      } else {
        this[prop] = 0
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button @click="chooseOne('one')">
      {{ one }}
     </button>
  <button @click="chooseOne('two')">
      {{ two }} 
     </button>
  <button @click="chooseOne('three')">
      {{ three }}
     </button>
</div>

Answer №2

It seems like your initial conditional statement is incorrect. The condition you have set is if (x == 1) else variable one will be reset to 0. However, when the second or third button is clicked and x is not equal to 1, the button's text resets even though there is no direct connection between these buttons.

new Vue({
  el: "#app",
  data: {
    one: 0,
    two: 0,
    three: 0
  },
  methods: {
    chooseOne: function(x, y) {
      if (x == 1) {
        if ((x == 1) && (this.one < 3)) {
          this.one++;
        } else {
          this.one = 0
        }
      }
      if (x == 2) {
        if ((x == 2) && (this.two < 3)) {
          this.two++;
        } else {
          this.two = 0
        }
      }
      if (x == 3) {
        if ((x == 3) && (this.three < 3)) {
          this.three++
        } else {
          this.three = 0
        }
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button @click="chooseOne(1,one)">
      {{ one }}
     </button>
  <button @click="chooseOne(2,two)">
      {{ two }} 
     </button>
  <button @click="chooseOne(3,three)">
      {{ three }}
     </button>
</div>

Answer №3

There seems to be an issue with the condition check in your code. Consider trying this solution instead:

chooseOne(x, y) {
      if (x == 1) {
        this.one <3  ? this.one++ : this.one = 0
      } 
      if (x == 2) {
      this.two <3  ? this.two++ : this.two = 0
      }
      if (x == 3) {
       this.three < 3 ? this.three++ : this.three = 0
      }
    }

Answer №4

It is important to practice writing DRY (Don't Repeat Yourself) code when developing software:

Vue.config.productionTip = false;
Vue.config.devtools = false;

new Vue({
  el: "#app",
  data: {
    one: 0,
    two: 0,
    three: 0,
    buttons: ['one', 'two', 'three']
  },
  methods: {
    chooseOne: function(y) {
      this[y] = this[y] < 3 ? this[y] + 1 : 0
    },
    getButton(button) {
      return this[button];
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button v-for="button in buttons" @click="chooseOne(button)">
      {{ getButton(button) }}
  </button>
</div>

By following the DRY principle, all your buttons go through the same process, eliminating the risk of inconsistencies, making the code more reliable.

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

Issue encountered when retrieving the ID of the active tab in a Google Chrome extension using Manifest V3: Uncaught TypeError - Unable to access properties of undefined while trying to read 'id'

Currently, I am facing a persistent error while creating a Google Chrome extension in Manifest V3: Error: Uncaught TypeError: Cannot read properties of undefined (reading 'id') Despite extensive research, I keep running into different errors w ...

AngularJS directive for incorporating additional directives lacks functionality

My current project involves creating a directive that will add form groups to a specific div. I'm working on this by linking the directive to a button in my html code. The functionality I am trying to achieve is quite simple, akin to what is shown in ...

Exploring Jasmine and AngularJS: Testing a factory function in the context of dependency injection

Looking to create a unit test for a simple factory that calculates the sum of two numbers. (function () { "use strict"; angular .module("math") .factory("addservice", [addTwoNumbers]); function addTwoNumbers(a, b) { ...

A script page in Wordpress generates a numerical value in the URL

I created a script named search.php which utilizes various search engines APIs to display search results. From this file, I have developed a Page template and incorporated the simplePagination plugin The issue arises when I click on a page within the pag ...

Obtain the value of the jQuery UI slider by interacting with the

Is there a ready-made solution available for displaying the slider value within the handle itself? Something like this: $( "#slider-vertical" ).slider({ orientation: "vertical", range: "min", min: 0, max: 100, v ...

What is the best way to import files in nodejs for tsc build and ts-node-dev compatibility?

While working with ts-node-dev, I have noticed that imported files must be named as "./api" or "./api.ts" during development. However, once the project is built using tsc, the file name needs to be "./api.js" (which is the sta ...

Submitting requests in Node.js Express

Can a request for a specific route be dropped using Node.js and express? For example, not returning an HTTP status or any headers, but simply closing the connection? app.get('/drop', function(req, res) { //What is the method to drop the requ ...

Is it possible for the *ngIf directive to stop unauthorized users from accessing my admin page through their browsers?

When the *ngIf directive is set to false, a certain element or component will not be included in the DOM. For example, let's say there is a component that displays admin tools and should only be accessible to authorized users (administrators). Will se ...

"Implementing Spring WebFlux to enhance security with JWT and CSRF tokens

I have a backend that needs CSRF protection implementation. The current configurations I am using allow Post and Get requests without the CSRF token. Here is my SecurityConfig: @Slf4j @EnableWebFluxSecurity @EnableReactiveMethodSecurity public class Securi ...

Confusion in JSON encoding, parsing, and function calling

After my server sends a JSON encoded array to the client, the client uses JSON.parse on it. However, when I try to extract the data, I encounter an error: TypeError: Cannot read property 'description' of undefined. Despite being certain that desc ...

Should loaders be utilized in an Angular application?

Webpack configuration allows the use of various loaders, such as file-loader, html-loader, css-loader, json-loader, raw-loader, style-loader, to-string-loader, url-loader, and awesome-typescript-loader. Does Angular have built-in knowledge of loaders with ...

Can I obtain a link through the branch_match_id parameter?

Within my application, there exists a hyperlink: hxxp://get.livesoccer.io/IuKk/0CRq5vArLx which leads to the following destination: hxxp://livesoccer.io/news.html?url=http%3A%2F%2Fwww.90min.com%2Fembed%2Fposts%2F4003374-chelsea-star-pedro-loving-life-at-s ...

Utilizing ng For in a personalized directive to fill a selection menu

I encountered an issue while trying to populate a selected dropdown using ngRepeat inside a custom directive. I came across this example that seemed similar to what I wanted to achieve here. Although it worked for the example, it didn't work for me. ...

Can a FilePicker be Cleared Automatically through Code?

Currently, I am implementing an‘<input type="file" . . .’ to select files individually and then attach them to a table located right under the file picker. This functionality is quite similar to using the attachment button on a SharePoint form’s r ...

Implement a time delay in the jQuery each function following an AJAX request

Here's an example of an XML document: <?xml version="1.0" encoding="UTF-8"?> <testimonials> <testimonial user="User Name 1" state="1" comment="Comment 1"></testimonial> <testimonial user="User Name 2" state="2" comm ...

There seems to be an issue with the functionality of the operators in the Calculator Javascript

I'm currently working on a Javascript calculator project for FreeCodeCamp and encountering an issue with the code. Whenever I input an operator like "-", "+", "x", etc., the numbers in the history section start repeating themselves. For example, if I ...

Clearing up memory in ThreeJS application

I'm facing challenges with memory management in my ThreeJS application. I know there are already a few queries regarding this issue: freeing memory in three.js Freeing memory with threejs Three.js Collada - What's the proper way to dispose() a ...

Can JavaScript be used to modify the headers of an HTTP request?

Can JavaScript be used to modify or establish HTTP request headers? ...

Attempting to modify the background color of an iFrame in Internet Explorer

I am experiencing an issue with my webpage where the iFrame is displaying with a white background in IE, while it shows up with a blue background in Firefox and Chrome. I have attempted various solutions to make the background of the iframe blue or transpa ...

What could be causing npm to fail to launch?

Whenever I execute node app.js, my server functions perfectly. However, when attempting to utilize nodemon for running the server, it fails to start. The error displayed by npm start is as follows: npm ERR! code ELIFECYCLE npm ERR! errno 9009 npm ERR! < ...