In Vue.js development, 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
import { ref } from 'vue';
const isDisabled = ref(true);
function toggleButton() {
isDisabled.value = !isDisabled.value;
}
Toggle Disabled State
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
import { ref, computed } from 'vue';
const name = ref('');
const email = ref('');
const isFormValid = computed(() => {
return name.value.trim() !== '' && email.value.includes('@');
});
Disable Button While Async Operation is in Progress
Useful when submitting forms, uploading files, or calling APIs.
Example – Simulate API Call
import { ref } from 'vue';
const loading = ref(false);
function handleClick() {
loading.value = true;
// Simulate async operation
setTimeout(() => {
alert('Done!');
loading.value = false;
}, 2000);
}
{{ loading ? ‘Processing…’ : ‘Submit’ }}
Also Read:
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
- Vue.js Docs: Reactivity in Composition API
- Vue.js Docs: Computed Properties