Disabling inputs conditionally in a Vue.js component is something that we may have to do sometimes.
In this article, we’ll look at how we can disable inputs conditionally in our Vue.js components.
Disabled Prop
To disable an input conditionally with Vue.js component, we can set the value of the disabled
prop.
For instance, we can write:
App.vue
<template>
<div id="app">
<input type="text" :disabled="disabled" />
<button @click="disabled = !disabled">toggle</button>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
disabled: false,
};
},
};
</script>
We have the disabled
state defined in the object we return in the data
method.
Then we have a button that toggles the disabled
prop between true
and false
.
Then in the input, we set the disabled
prop to the disabled
value.
Now the input will be toggled between enabled and disabled when we click on the toggle button.
We can also pass in a computed property to the disabled
prop.
For instance, we can write:
<template>
<div id="app">
<input type="text" :disabled="isDisabled" />
<button @click="count++">increment</button>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
count: 0,
};
},
computed: {
isDisabled() {
return this.count === 3;
},
},
};
</script>
We have the count
state which the isDisabled
computed property is derived from.
We return true
is this.count
is 3.
The increment button increases the count
value by 1 each time we click it.
Therefore, when we click increment and the count
is set to 3, we see the input disabled.
Conclusion
We can disable input values with the disable
prop on the input.
We can set it to a state or a computed property.