Reputation: 1748
I have a login button that would navigate to the route dashboard/
when a login is successful. The button works on click but when I press the enter key it duplicates the route.
So the flow is this:
At which point the address becomes http://localhost:3000/dashboard/dashboard/
instead of just http://localhost:3000/dashboard/
. What's even more weird is that if I follow the same flow as above but I click the button instead. It works as expected no matter how many times I press the back button. The stripped component is shown below.
<template >
<v-container>
<v-row justify="center">
<v-col cols='6' align="center">
<v-form>
<h1 class="pb-4">Login</h1>
<v-text-field
label="Email"
placeholder="[email protected]"
>
</v-text-field>
<v-text-field
label="Password"
type="password"
>
</v-text-field>
<v-btn dark block @click="login"> Login </v-btn>
<br />
<a href="">Forgot your password?</a>
</v-form>
</v-col>
</v-row>
</v-container>
</template>
<script>
export default {
data() {
return {
showPassword: false,
};
},
mounted(){
document.addEventListener("keyup", (event) => {
if (event.key ==='Enter') {
this.login();
}
});
},
methods: {
async login() {
try {
//throw 'Login is not setup'
//do login logic
this.$router.push({ path: "dashboard/" });
} catch (error) {
console.error(error);
}
},
},
};
</script>
<style>
</style>
Upvotes: 0
Views: 182
Reputation: 728
I think your problem is the way you have an event set up with an event listener, which you technically shouldn't need since the native and normal behavior for a form is to submit on enter. Instead of having a click event on your button, use a button type of submit and a prevent default behavior on the form to catch the normal form submission and instead run your submit function. This should then work the same for clicking the button or hitting enter.
Template:
<form @submit.prevent="login()">
<button type="submit">submit</button>
</form>
export default {
methods: {
login() {
// stuff you want to do
},
}
Vuetify should have ways to set it's properties up to do the same as vanilla forms. But the idea should work the same.
Upvotes: 2