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

Adjust the column count in mat-grid-list upon the initial loading of the component

My goal is to implement a mat-grid-list of images with a dynamic number of columns based on the screen size. Everything works perfectly except for one small glitch – when the grid first loads, it defaults to 3 columns regardless of the screen size until ...

Disabling the Bootstrap tooltip feature is a quick and easy process

Is there a way to turn off bootstrap tooltip on my website? I activated it with the code below: function activateTooltip() { const toolTips = document.querySelectorAll('.tooltip'); toolTips.forEach(t => { new bootstrap.Tooltip(t); } ...

The WebSocket connection in the browser, when accessed through a remote server, typically shows a CLOSED state in the readyState property during the on

Local server operations are running smoothly. However, when testing on a remote server with Nginx, the issue arises where the readyState inside the event handler onopen is consistently showing as CLOSED. Nginx configuration: server { server_name doma ...

Receiving an unexpected error message related to Vuex in the watcher function, even though I am not utilizing Vuex in my N

My goal is to update an object property in an array [{ text: 'some text' value: 'some value, active: false }, etc..] from false to true when I click on a checkbox that is connected to a v-model: <v-col v-for="(item, i) in searchModul ...

No matter how hard I try, I can't seem to get any of my jQuery events to function properly on my

Help! I'm encountering issues with jQuery on my webpage. It's not functioning at all, despite my extensive search for a solution. Feeling desperate, I'm reaching out for assistance here. Below are my HTML and JS files: HTML <html> ...

Tips for activating autocomplete / IntelliSence for sass within vue documents on VS Code platform?

Despite using lang="sass" in my .vue files within VS Code, I am experiencing issues with the autocomplete feature for CSS properties. (Vetur is already installed on my system) Is there anyone who can provide a solution or suggest settings that need to be ...

Having trouble with gapi.client.request() not functioning properly?

I've been trying to use the Google API for freebase, and even though I'm following the correct call as per the documentation, it seems like there is an issue. The Chrome debugger is showing that something is wrong with this supposedly simple call ...

Tips on maintaining the numerical value while using JSON.stringify()

Having trouble using the JSON.stringify() method to convert some values into JSON format. The variable amount is a string and I want the final value in JSON format to be a number, but it's not working as expected. Even after applying JSON.stringify(), ...

Integrate a character key feature to cycle through options in a customized Vue select component

In my Vue/Nuxt.js project, I have implemented a custom select component with arrow key functionality for scrolling through options and selecting with the enter key. Now, I am trying to add "jump key" functionality where pressing a character key will jump t ...

React Object is throwing an error - not a function

I need assistance resolving this issue. The error Object(...) is not a function keeps appearing in my code. Here is the snippet of code that seems to be causing the problem: It centers around the declaration of const useStyles = makeStyles(() => ({. ...

Whenever my code is used within Google Sites, it triggers the opening of a new and empty tab

When using this code inside an HTML box in Google Sites, a problem arises. It seems to work perfectly fine in Internet Explorer and Chrome when saved to an HTML file. However, within Google Sites, it unexpectedly opens a new tab with no data. The code st ...

What is the mechanism behind range traversal in Javascript?

Exploring the createRange() function and related constructs in Javascript has sparked my curiosity about its practical applications. During my search, I stumbled upon an interesting application called "" that allows users to highlight text with mouse clic ...

Adapting Classes in Javascript Based on Screen Width: A Step-by-Step Guide

I'm dealing with two separate menus - one for mobile version and one for PC version. However, the mobile menu seems to be overlapping/blocking the PC menu. How can I resolve this issue? I've attempted various solutions such as removing the mobil ...

Utilizing JavaScript to Parse RSS XML Feeds Across Domains

Looking to parse an RSS (XML) file without relying on the Google RSS feed. I have attempted using JSONP, but it resulted in downloading the file and throwing an error "Uncaught SyntaxError: Unexpected token < ". $.ajax({ type: "GET", ur ...

Concealed Input Enhancements for AutoComplete

Hey there! I'm new to AJAX and could really use some help with my autocomplete function. I'm trying to store the ID of the user's selection in a hidden input field, but I've hit a roadblock. So far, my function isn't working as exp ...

Utilizing Bootstrap CSS within Vue's scope

I'm attempting to integrate Bootstrap into a Vue component while ensuring that all CSS is scoped. My initial approach was as follows: <style scoped> @import "~bootstrap/dist/css/bootstrap.css"; @import "~bootstrap-vue/dist/bootstrap-vue.css"; & ...

Node.js npm-migration enables the creation of multiple tables in a single migration process

I am new to npm-migration for nodejs and I am exploring ways to streamline the process of creating multiple tables using a single migration, rather than having separate migrations for each table creation. I have experimented with the following code: "up": ...

The dropdown menu is extending outside the header in a right-to-left (RTL) direction

I have implemented the jQuery code below to prevent the dropdown from extending beyond the header area. It works perfectly in the normal LTR version. However, I need a solution for the RTL version. How can I achieve this? jQuery $('.primary-menu .dr ...

Incorporate a comma after the second or third digit to separate currency values in JavaScript

Is there a way to add commas to currency values at the 3rd or 2nd place depending on the value itself? The desired output format is: 1000 => 1000 10000 => 10,000 210000 => 2,10,000 2010000 => 20,10,000 12010000 => 1,20,10,000 I am currentl ...

Accessing props in react-native-testing-library and styled-components is not possible

I defined a styled-component as shown below: export const StyledButton = styled.TouchableOpacity<IButtonProps> height: 46px; width: 100%; display: flex; flex-direction: row; justify-content: center; align-items: center; height: 46px; ...