Categories
Vue Answers

How to disable input conditionally with Vue.js?

Spread the love

We can disable an input conditionally in Vue.js by using the v-bind directive (or shorthand :) to bind the disabled attribute to a boolean expression.

For instance we write

<template>
  <div>
    <input type="text" v-model="inputValue" :disabled="isDisabled">
    <button @click="toggleDisabled">Toggle Input</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      inputValue: '',
      isDisabled: false
    };
  },
  methods: {
    toggleDisabled() {
      this.isDisabled = !this.isDisabled;
    }
  }
};
</script>

In this example we have an <input> element with the v-model directive to bind its value to the inputValue data property.

We also use the :disabled directive to conditionally disable the input based on the value of the isDisabled data property.

There’s a button that, when clicked, toggles the value of the isDisabled property between true and false.

When isDisabled is true, the input will be disabled. Otherwise, it will be enabled.

We can adjust the condition for disabling the input based on your specific requirements.

This is a common approach in Vue.js to conditionally disable elements based on dynamic data properties.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *