Skip to content
vue

How to disable input in Vue.js conditionally

Sep 10, 2024Abhishek EH1 Min Read
How to disable input in Vue.js conditionally

You can use the v-bind (or shorthand :) to bind attributes dynamically in Vue.js. To disable the input you can bind the disabled attribute to isDisabled data property.

1<template>
2 <div>
3 <input type="text" :disabled="isDisabled" placeholder="Enter text here" />
4 <button @click="toggleDisable">Toggle Disable</button>
5 </div>
6</template>
7
8<script>
9export default {
10 data() {
11 return {
12 isDisabled: false
13 };
14 },
15 methods: {
16 toggleDisable() {
17 this.isDisabled = !this.isDisabled;
18 }
19 }
20};
21</script>

In the above code, we have a button, when clicked will disable and enable the input.

If you have more complex scenario like to disable the submit button until the form has some value, you can use the below code:

1<template>
2 <div>
3 <form>
4 <input v-model="name" type="text" placeholder="Name" />
5 <input v-model="email" type="email" placeholder="Email" />
6 <button :disabled="!isFormValid" type="submit">Submit</button>
7 </form>
8 </div>
9</template>
10
11<script>
12export default {
13 data() {
14 return {
15 name: '',
16 email: ''
17 };
18 },
19 computed: {
20 isFormValid() {
21 return this.name.length > 0 && this.email.length > 0;
22 }
23 }
24};
25</script>

In the above code we check if there is some value in both name and email, then only enable the submit button.

If you have liked article, stay in touch with me by following me on twitter.

Leave a Comment

© 2024 CodingDeft.Com