I'd bind a button to input using v-bind with a function :
The code inside my template :
<template>
<input
type="email"
v-model="email"
v-bind:placeholder="$t('fields.email_place_holder')"
/>
<input
v-bind:disabled="{ isDisable }"
type="submit"
v-bind:value="$t('buttons.notify_me')"
class="notify-me-button"
/>
</template>
The code inside my script :
methods: {
isDisable() {
return email.lenght > 0;
}
}
But the button
does not change its status , I tried to change the css style with the same way and the result is the same.The problem is that button responds once time on the first value returned by isDisable()
.
The button isn't disabled because the binding disabled=isDisable
is not reactive.
It's not reactive because the bound value isDisable
is not a reactive property (in either data
or computed
) and it is not a method that has any reactive parameters i.e. it's called once/evaluated to the constant false
. Vue won't check if there's reactive properties in the method body, after all methods are supposed to explicitly called in your code.
There's few ways you can fix this:
isDisable
a computed property instead:computed: {
isDisable() {
return this.email.length > 0;
}
}
email
) as a parameter to your method so Vue knows to update the binding.<input
type="submit"
:disabled="isDisable(email)"
/>
methods: {
isDisable(email) {
return email.length > 0;
}
}
email
). This is allowed.<input
type="submit"
:disabled="email.length > 0"
/>
Working example on JS Fiddle
These would be the obvious (and perhaps idiomatic) approaches to fix this, but there are others e.g. using a watcher.
Note there's also typos in your provided code, e.g.:
:disabled="{isDisable}"
is an not a valid binding due to the curly bracesisDisable(){ return email.lenght > 0 }
should be length
not lenght
The easy way to do it is to check if the value exists or not. For example:
<input type="text" v-model="user.name" required />
For the submit button just use disable
<button type="submit" :disabled="!user.name">Submit</button>
Only when the field is filled then the submit button is enabled for submit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With