简体   繁体   中英

Vue Prevent form submit when pressing enter inside form

I have a webapp with multiple forms and inside these forms multiple custom made components: input, textarea, selectbox, datepicker, radiobutton, checkbox, ... .

I found out that the submit function is fired when pressing the enter key inside a child component of a form tag. Something I don't want. I want to be able to use the enter key for other things like conforming a selection in a dropdown.

Form example

<template>
    <form @submit.prevent="handleLogin">
        <fieldset :disabled="isSubmitting" class="space-y-6">
            <Input :label="$tc('email', 1)" type="email" id="email" v-model="user.email" :error="errors.email" />
            <Input :label="$tc('password', 1)" type="password" id="password" v-model="user.password" :error="errors.password" />
            <Select :label="$tc('role', 1)" id="role" :options="roles" displayProperty="display_name" valueProperty="id" v-model="user.role" :error="errors.role" />
            <SubmitButton :label="$tc('register', 1)" :submittingLabel="$tc('register_loader', 1)" :isSubmitting="isSubmitting" />
        </fieldset>
    </form>
</template>

SubmitButton.vue

<button type="submit">{{ isSubmitting ? submittingLabel : label }}</button>

Therefore I'm looking for a way to prevent the default behaviour. Adding a keydown function and checking if the enter key is being pressed inside all the custom components followed by an event.preventDefault() didn't do the trick.

A working solution should be to change the type of the button from 'submit' to 'button' and use an @click but that doesn't sound like semantic html.

Any other suggestions?

You can prevent submission on enter key down just annotating the top-level form.

<form @submit.prevent="handleLogin" @keydown.enter="$event.preventDefault()">

You can see it in action

I think

<form v-on:submit.prevent="onSubmit"></form>

should do the trick. If not, take a look at Event-Modifiers to find the one that best suite your use case. happy coding!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM