Reputation: 1973
I have an email input and a watcher that checks if the input is valid or not. However, the watch event only gets triggered when you type something on the email field. The email field has an existing value that may or may not be invalid. An x is displayed if the email is invalid and a check otherwise. However, since the email has an existing value, the check is initially displayed even when the input is invalid. If the user clears the email field, and retypes the invalid email, that's the only time the watcher will be triggered and the x will be displayed.
Here's my vue instance:
var register = new Vue({
el: '#register',
data: {
email: document.getElementById('profileEmail').value,
isEmailTaken: false,
emailTimer: null,
emailBusy: false
},
methods: {
validateEmail: function(email) {
var self = this;
var url '/api/users?email=' + email;
self.$http.get(url)
.then(function(res){
self.isEmailTaken = true;
self.emailBusy = false;
}, function(err){
self.isEmailTaken = false;
self.emailbusy = false;
});
},
watch: {
email: function(val) {
var self = this;
clearTimeout(self.emailTimer);
self.emailBusy = true;
self.emailTimer = setTimeout(function() {
self.validateEmail(val);
}, 1600);
}
}
}
This is my email input (in pug):
.form-group
label Email Address
.input-group
input.form-control(type="email" name="emailAddress" value=profile.email
v-model="email"
v-validate
data-vv-delay="1000"
data-vv-rules="required|email"
data-vv-as="email"
:class="{ 'input': true, 'is-danger': errors.has('emailAddress') }"
placeholder="eg. [email protected]")
.input-group-append
span.input-group-text
i.fal.fa-pulse.fa-spinner(v-if="email && emailBusy")
i.fal.fa-check.text-green(v-if="email && !emailBusy && !isEmailTaken && !errors.has('emailAddress')")
i.fal.fa-times.text-red(v-if="email && !emailBusy && (isEmailTaken || errors.has('emailAddress'))")
Upvotes: 1
Views: 12118
Reputation: 20845
Vue has an option for this.
immediate: true
. Meaning that the watch function will be executed with the initial value in the beginning as well. See Option: immediate in the api doc.
export default {
//...
watch: {
email: {
handler: function(val) {
/* ... */
},
immediate: true
}
}
//...
};
Upvotes: 6