[Vuejs]-Is it possible to bind a class to an element based on a boolean expression?

0๐Ÿ‘

โœ…

I think Iโ€™ve found a pretty good solution. I used a method with an argument instead of computed properties:

<template>
  <form @submit.prevent="onSubmit" novalidate>
    <input
      type="email"
      :class="{ invalid: isInvalid($v.email.$error) }"
      v-model.lazy="email">
    <button type="submit">Submit</button>
  </form>
</template>

<script>
import { required, email } from 'vuelidate/lib/validators'

export default {
  data () {
    return {
      email: '',
      submitted: false
    }
  },
  validations: {
    email: {
      required,
      email
    },
  },
  methods: {
    isInvalid (val) {
      return val && this.submitted
    },
    onSubmit () {
      this.submitted = true
      if (!this.$v.$invalid) {
        // do something with the email address
      }
    }
  }
}
</script>

0๐Ÿ‘

<input type="email" :class="{ invalid: formValid($v.email.$error) }">

    computed: {
        formValid(){
           return (val) {
                val && this.submitted ? true : false
            }
         }     
    }

Could you test this out im curious if it would work, then you just have to pass a param and need one Computed.

0๐Ÿ‘

Your Code

<input type="email" :class="{ invalid: submitted && $v.email.$error }">

The problem here, even though you defined $v in your local state, Vue is unable to find it. Try to define your local state in your data property without a preceding dollar sign. Because $ carries an extra meaning in Vue.

Generally $ means instance properties like data, el, root, children etc.
For example to access what element your Vue instance is mounted on, you can use this.$el.
So you can modify your code like this โ€“

<input type="email" :class="{ invalid: submitted && $data.$v.email.$error }">

Leave a comment