Within my Vue JS application, I have implemented code that changes the color of text based on a meter value. The code snippet looks like this:
<span class="card__form__meter__warning" :class=" { weak : password_weak, 'very-weak' : password_veryweak, strong : password_strong, valid : password_verystrong } ">{{ password_warning }}</span>
While the above code works, I believe it is overly repetitive and there must be a simpler way to achieve the same result:
data: {
name: null,
emailAddress: null,
password: null,
password_warning: 'Strong password required',
password_veryweak: false,
password_weak: false,
password_strong: false,
password_verystrong: false,
...
if (this.meter == 0) {
this.password_veryweak = false
this.password_warning = 'Strong password required'
}
if ( this.meter == 25) {
this.password_warning = 'Very weak (not strong enough)'
this.password_veryweak = true
this.password_weak = false
this.password_strong = false
this.password_verystrong = false
}
if (this.meter == 50 ) {
this.password_warning = 'Weak (not strong enough)'
this.password_weak = true
this.password_veryweak = false
this.password_strong = false
this.password_verystrong = false
}
if (this.meter == 75) {
this.password_warning = 'Strong'
this.password_strong = true
this.password_verystrong = false
this.password_weak = false
this.password_veryweak = false
}
if (this.meter > 75) {
this.password_warning = 'Very Strong'
this.password_verystrong = true
this.password_strong = false
this.password_weak = false
this.password_veryweak = false
}
I encountered difficulties when trying to remove previous conditional classes as the meter values changed, which led me to set the
this.password_weak = false
this.password_strong = false
this.password_verystrong = false
for each condition.
If you have any insights or suggestions, I would greatly appreciate your help.
Thank you!
-----edit-------
computed: {
password_warning: function () {
if (this.meter == 0) {
this.password_class = ''
return 'Strong password required'
} else if (this.meter == 25) {
this.password_class = 'very-weak'
return 'Very weak (not strong enough)'
} else if (this.meter == 50) {
this.password_class = 'weak'
return 'weak (not strong enough)'
} else if (this.meter == 75) {
this.password_class = 'strong'
return 'Strong'
} else {
this.password_class = 'strong'
return 'Very strong'
}
},
}