Within my Vue.js application, I've implemented a login form that I'd like to shake whenever a login attempt fails.
Though I have achieved the desired shaking effect, I'm not completely satisfied with my current solution. Here's a simplified version of my code:
const Home = {
data() {
return {
shakeForm: false
}
},
template: `
<div>
<form :class="{'form-shaking': shakeForm}"
@submit.prevent="login"
@animationend="shakeForm = false;"
>
form fields
</form>
</div>
`,
methods: {
async login() {
// ...
const rawResponse = await fetchLogin();
if (!rawResponse.ok) {
this.shakeForm = true;
return;
}
// login successful
}
}
};
.form-shaking {
position: relative;
animation: shake-horizontally .2s ease-out 2;
}
@keyframes shake-horizontally {
from {
left: 0;
}
25% {
left: 25px;
}
75% {
left: -25px;
}
to {
left: 0;
}
}
In essence, I am toggling the shakeForm
boolean property to dynamically apply and remove the form-shaking
class on the <form>
element when needed. The class is removed upon completion of the shaking animation to enable it to play again.
I am curious if there is a specific feature within Vue.js designed to handle situations like this. I explored transition and animation capabilities but did not come across a suitable alternative.