Marc Pont
Marc Pont

Reputation: 1078

Vue.js: Is there a way to have @submit.prevent on all the forms of a project?

I'm realizing there are some snippets that I'm repeating everytime, and sometimes I forget.

One of them is the @submit.prevent. In all forms I have to write it for preventing to submit, I'll always manage the submission through a vue method.

So can I do something that all forms have this instruction implicitly?

Upvotes: 0

Views: 178

Answers (1)

Excalibaard
Excalibaard

Reputation: 2073

You can create a simple (probably functional) component and use this instead of the normal <form>.

// BaseForm.vue

<template>
  <form @submit.prevent="onSubmit">
    <slot />
  </form>
</template>

<script>
export default {
  props: {
    onSubmit: {
      type: Function,
      required: true,
    }
  }
}
</script>

You won't really save a lot of code, but you won't have to think about it anymore. You could include the basic <button type=submit></button> in here as well.

Upvotes: 1

Related Questions