Conditionally enable/disable HTML attributes in Vue.js

in Code Write a comment

In this tutorial, you’ll learn how to conditionally enable/disable HTML attributes in Vue.js components.

In Vue.js you can enable or disable an HTML button or form field, make it required or optional using multiple ways.

Using computed property

I’ve described how to conditionally disable the input field using the computed property. Here’s the example.

<div id="app">
  <h2>Please, verify your email address:</h2>
  <input type="text" id="email" name="name" v-model="email" :disabled="validated ? '' : disabled" /><br><br>
  <h4 v-if="validated">
    Thank you for verifying your email address
  </h4>
</div>

We’re checking the HTML attribute disabled against the computed property validated().

If validated is true the input field will become disabled.

Using data object

We can check HTML attributes against the data() object values.

<div id="app">
  <h2>Please, verify your email address:</h2>
  <input type="text" id="email" name="name" v-model="email" :disabled="!emailEnabled" /><br><br>
  <h4 v-if="validated">
    Thank you for verifying your email address
  </h4>
</div>

emailEnabled is set to false, therefore, the email field is disabled.

new Vue({
  el: "#app",
  data: {
    email: null,
    correctEmail: '[email protected]',
    emailEnabled: false
  },
  methods: {
  },
  computed: {
    validated() {
      if (this.email === this.correctEmail) {
      	return true
      }
    },
  }
})

We can enable/disable other HTML attributes the same way, e.g. required.

<input type="text" id="email" name="name" v-model="email" :required="emailRequired" />

If you find this post useful, please let me know in the comments below. 
Cheers,
Renat Galyamov

Want to share this with your friends?
👉renatello.com/vue-js-html-attributes

PS: Make sure you check other Vue.js tutorials, e.g. Top 5 CSS frameworks for your Vue.js project (2019)how to programmatically navigate use router in Vue.js.

Write a Comment

Comment