In Vue.js, controlling the disabled state of a button is a common UI task especially for forms, validations, or async operations. Vue makes this easy using the :disabled directive, which binds a Boolean condition to the button’s disabled attribute.

Disable Button Based on Data or State

You can bind the disabled attribute to a ref or data property.

Example – Toggle Button Enabled State

<!– ToggleButton.vue –><script setup>import { ref } from ‘vue’;

 

const isDisabled = ref(true);

 

function toggleButton() {

  isDisabled.value = !isDisabled.value;

}

</script>

 

<template>

  <button :disabled=”isDisabled”>Click Me</button>

  <br />

  <button @click=”toggleButton”>

    Toggle Disabled State

  </button>

</template>

Disable Button During Form Validation

Use a computed property to determine if a form is valid, and disable the submit button accordingly.

Example – Basic Validation

<!– FormValidation.vue –><script setup>

import { ref, computed } from ‘vue’;

 

const name = ref(”);

const email = ref(”);

 

const isFormValid = computed(() => {

  return name.value.trim() !== ” && email.value.includes(‘@’);

});

</script>

 

<template>

  <input v-model=”name” placeholder=”Name” />

  <input v-model=”email” placeholder=”Email” />

  <button :disabled=”!isFormValid”>Submit</button>

</template>

Disable Button While Async Operation is in Progress

Useful when submitting forms, uploading files, or calling APIs.

Example – Simulate API Call

<!– AsyncButton.vue –><script setup>

import { ref } from ‘vue’;

 

const loading = ref(false);

 

function handleClick() {

  loading.value = true;

 

  // Simulate async operation

  setTimeout(() => {

    alert(‘Done!’);

    loading.value = false;

  }, 2000);

}

</script>

 

<template>

  <button :disabled=”loading” @click=”handleClick”>

    {{ loading ? ‘Processing…’ : ‘Submit’ }}

  </button>

</template>

Also Read: The Vue JS Best Practices In Detail

Best Practices

  • Use :disabled with reactive data or computed properties.
  • Provide visual feedback (e.g., spinner or text change) during loading.
  • Always handle edge cases where a button may be unintentionally re-enabled too soon.

Key Takeaway

To disable buttons in Vue.js, bind the disabled attribute to a reactive variable or computed condition using :disabled. This ensures your UI reflects the latest logic based on user input, loading states, or validation rules.

Related Resources