How can I conditionally disable a button in Vue.js using an if statement?

Can someone help me figure out why all my buttons are getting disabled when I only want one to be disabled? Here is the code where I created a counter with vue.js:

     <body> 
      <div id="app">
        <button @click="count++" v-bind:disabled="blockCount">increment</button>
        <button @click="count--">decrement</button>
        <p>The count is {{ count }}</p>
        <p>{{ message }}</p>
        <button v-on:click="reverseMessage">Reverse Message</button>
        <p v-if="count >= 7" blockCountChange()> </p>
 </div>

<script>
 const example1 = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue ! Just a test',
    count:'',
    blockCount: false
  },
  methods: {
    reverseMessage: function () {
      this.message = this.message.split(' ').reverse().join(' ')
  },
  blockCountChange: {
      function() {
        if (this.count>5) {
          return this.blockCount = true;
      }   
     }
    }
  } 
});  
</script>
  </body>

Answer №1

There seems to be a lot of random asterisks scattered throughout the code, but I believe you were aiming to implement a computed property

export default {
  data() {
    return {
        count: 0,
    }
  },
  computed: {
    blockCount() {
      return this.count > 5
    }
  }
}

Answer №2

With Vue, all data properties are encapsulated in a reactive proxy. This means that any element using the property will automatically receive an event when the value is changed. You no longer have to manually update the value of blockCount. Instead, you can use a computed property to track the count value and return a precomputed result.

By doing this, you can also eliminate the

<p v-if="count >= 7" blockCountChange()> </p>

which seems to be the root cause of the issue you are experiencing.

This simplifies your code to:

<body>
    <div id="app">
        <button @click="count++" :disabled="blockCount">increment</button>
        <button @click="count--">decrement</button>
        <p>The count is {{ count }}</p>
        <p>{{ message }}</p>
        <button @click="reverseMessage">Reverse Message</button>
    </div>

    <script>
        const example1 = new Vue({
            el: "#app",
            data() {
                return {
                     message: "Hello Vue ! Just a test",
                     count: 0,//this is a number so use a number
                }
            },
            computed:{
                blockCount(){
                    return this.count > 5
                }
            },
            methods: {
                reverseMessage() {
                    this.message = this.message.split(" ").reverse().join(" ");
                },
            },
        });
    </script>
</body>

It's important to note that the data property should be a function returning the default value. Specifying an object will cause each instance of your Vue object to share the same memory space, leading to conflicts.

Answer №3

Utilize a computed property to dynamically retrieve the value of blockCount.

See it in action :

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue ! Just a test',
    count: '',
    blockCount: false
  },
  computed: {
    getblockCount() {
        this.blockCount = this.count > 5
      return this.blockCount;
    }
  },
  methods: {
    reverseMessage: function () {
      this.message = this.message.split(' ').reverse().join(' ')
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
        <button @click="count++" :disabled="getblockCount">increment</button>
        <button @click="count--">decrement</button>
        <p>The count is {{ count }}</p>
      <p>{{ message }}</p>
      <button v-on:click="reverseMessage">Reverse Message</button>
     <p> <span v-if="count >= 5">You click on the counter enough ! STOP IT !</span></p>
 </div>

Answer №4

Take a look at this illustration

We can apply a watcher to track and log actions we wish to perform.

new Vue({
    el: '#app',
    data: {
        message: 'Hello Vue ! Just experimenting',
        count: 0,
        question: '',
        incrementDesabled: false,
        decrementDesabled: true
    },
    watch: {
       // whenever count changes, this function will execute
        count(newCount, oldCount) {
           if(newCount == 0){
               this.decrementDesabled = true;
           }
           else if(newCount >= 5){
               this.incrementDesabled = true;
               this.decrementDesabled = false;
           }else if(newCount <= 5){
               this.incrementDesabled = false;
               this.decrementDesabled = false;
           }
        }
    },
    methods: {
        reverseMessage: function () {
            this.message = this.message.split(' ').reverse().join(' ')
        }
    }
});
<body>
        <div id="app">
            <button @click="count++" v-bind:disabled="incrementDesabled">increase</button>
            <button @click="count--" v-bind:disabled="decrementDesabled">decrease</button>
            <p>The counter is {{ count }}</p>
            <p>{{ message }}</p>
            <button v-on:click="reverseMessage">Reverse Message</button>
        </div>
        <script src="index.pack.js"></script>
    </body>

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

Currently struggling to retrieve data from an AJAX post request within a C# controller

I need assistance with sending data from JavaScript to a C# controller using AJAX. However, I am facing an issue where all the arguments in the Add method of my controller are showing up as null. Below is my AJAX code: function sendRequest(name, price, ab ...

What could be the reason for not receiving any response from my Firestore query?

Hey there! I'm delving into the world of Firebase for the first time and just set up the Firestore emulator. I've added some data that I want to fetch in my Nextjs app. Once I initialized firebase, this is what my component code looks like: funct ...

Updating the main Vue app's value from a Vuetify component in Vue - a step-by-step

I have two vue files, app.vue and logincomponent.vue. In logincomponent.vue, I created a template for a login box that communicates with the go backend in Wails. The code is working fine, but I am struggling to change the value in the main app.vue file. ...

Is it possible to include multiple API routes within a single file in NextJS's Pages directory?

Currently learning NextJS and delving into the API. Within the api folder, there is a default hello.js file containing an export default function that outputs a JSON response. If I decide to include another route, do I need to create a new file for it or ...

I developed a real estate listing web application using AngularJS, where I chose to use the $http service to fetch data. Unfortunately, the data retrieval process seems to be failing. Can someone help me identify the issue?

Hey there, I have identified three files which seem to be at the root of the problem. Instead of using POST, GET, PUT, DELETE methods, I am intentionally experimenting with $http. Let's take a look at mansionsController.js file: angular .module( ...

Incorporating a personalized image to create custom icons on the Material UI bottom navigation bar

Is it possible to replace the default icon with a custom image in material ui's BottomNavigation component? I'm curious if Material UI supports this feature. If you'd like to take a closer look, here is the link to the codesandbox. ...

What is the best way to position a div to float or hover from the bottom after it has been

I am working on creating a menu where clicking it will reveal a submenu at the bottom, but I'm encountering an issue. Currently, in my code, the submenu is appearing from right to left before moving down. Here is my code: <meta name="viewport" co ...

Having trouble getting Safari to load preflight CORS authentication requests (XHR) in a Vue.js application hosted on Apache?

I've been spending hours researching and trying to debug, but I'm not having any luck. This workflow/request works fine on Chrome, but Safari and Firefox both fail at the OPTIONS preflight request. Safari shows two errors: (!) Failed to load res ...

A configuration for ".node" files is missing: specifically, the loader for node_modules/fsevents/fsevents.node in a project using Vite

Everything was running smoothly in my Vite + React project until last week when out of nowhere, I encountered this error: No loader is configured for ".node" files: node_modules/fsevents/fsevents.node node_modules/fsevents/fsevents.js:13:23: 1 ...

Navigate directly to the section on the page that discusses the hashtag

So, I have a unique scenario to address. I'm working with two div elements where only one should be visible at a time. Here's the situation: The first div serves as an introduction page with a button that hides it and reveals the second div. Th ...

The JSON parsing functionality is not working as expected in my app.js file

app.js: const express = require("express"); const https = require("https"); const app = express(); const port = 3000; app.get("/",function(req,res){ const url ="https://maps.googleapis.com/maps/api/geocode/jsonaddress=1600+Amphitheatre+Parkway,+Mounta ...

Solving compatibility problems with jquery AJAX requests on multiple browsers

searchCompanyExecutives: function(criteria, callback) { var params = $j.extend({ type: "GET", data: criteria, url: "/wa/rs/company_executives?random=" + Math.floor(Math.random() * (new Date()).getTime() + 1), ...

Issue with using Sinon FakeServer with Mocha

I'm currently in the process of setting up a test for an API call. In my attempt to create a fake server within the before method, I have encountered issues with testing the basic implementation using $.ajax compared to my actual api call. Strangely, ...

Reacts Router Link does not refresh page content

My React and Redux application features a Movie component that displays movie data fetched from an API. To enhance user experience, I decided to create a Similar Movies section at the bottom of the page. This section contains components that allow users t ...

The jQuery animation concludes before its anticipated completion

I'm currently facing a small issue with a jQuery animation. The HTML code I have is as follows: <div id="menu"> <a id="menu-about" href="/">About...</a><br /> <a id="menu-ask" href="/">Ask me a question</a> ...

Setting a timeout from the frontend in the AWS apigClient can be accomplished by adjusting the

I am currently integrating the Amazon API Client Gateway into my project and I have successfully set up all the necessary requests and responses. Now, I am trying to implement a timeout feature by adding the following code snippet: apigClient.me ...

Having trouble with ReactJS rendering components?

FriendList.js var React = require('react'); var Friend = require('./friend.js'); var FriendList = React.createClass({ render: function() { return( <div> <h3& ...

Allow-Origin-Control, handler.php for emails, and form validation script

I encountered a strange bug recently. There's been some issues with the HTML5 template I downloaded, specifically related to the contact form and MailHandler.php file. Despite having both files in the same directory, when inspecting element in Chrome, ...

What is the most efficient method for appending /.json to the conclusion of express routes?

I am currently transitioning a DJANGO API to Node.js and have been tasked with ensuring that routes support the .json extension at the end. For instance, sending a GET request to /users/:id/.json should return a JSON object representing the user. The cha ...

Tips for resolving the GOOGLE_APPLICATION_CREDENTIALS issue when deploying Firebase hosting using GitHub CI/CD automation

I am currently working on a Vuejs project hosted on Firebase hosting with GitHub actions for CICD. I encountered the following error during deployment to Firebase. Below is my build-and-deploy.yml code: - name: Deploy to firebase uses: w9jds/<a hre ...