How to disable input conditionally in Vue.js

In this Vue.js tutorial, we will show you how to disable HTML input in Vue.js components conditionally.

To remove the disabled prop, you should set its value to false, which need to be the boolean value, not the string. If you need the input to be disabled in case of false, otherwise it should be enabled and editable.

Let’s consider this case. If the value for validated is either a 1 or a 0, then you should conditionally set the disabled prop based on that value:

<input type="text" :disabled="validated == 1">

Here’s the full example:

<!DOCTYPE html>
<html>
  <head>
    <title>Disable input  in Vue.js</title>
  </head>
  <body>
    <div id="app">
      <button @click="disabled = (disabled + 1) % 2">Switch</button>
      <input type="text" :disabled="disabled == 1" />
      <pre>{{ $data }}</pre>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <script>
      new Vue({
        el: "#app",
        data: {
          disabled: 0
        }
      });
    </script>
  </body>
</html>

Do you find this helpful?

Related articles