Conditionally add @submit.prevent to a form in Vue.js

Viewed 1349

I'm trying to conditionally prevent HTML form submission using @submit.prevent. I have a generic form model that looks like this (minimized a bit):

<v-form v-model="valid">
   <div>
      <div v-for="(field, i) in fieldConfig" :key="`model-form-`+i">
         <fe-label v-if="field.label">{{field.label}}</fe-label>
         <component 
            :is="field.component" 
            v-bind="field.attrs" 
            v-model="item[field.field]"
          />
       </div>
   </div>
</v-form>

Called from a parent:

<model-form
   idProperty="id"
   @done="finishRename"
   model="myModel"
   :fieldConfig="fieldConfig"
   :htmlSubmit="false"
/>

I've seen some similar things in my searching but nothing quite right, and I'm pretty raw when it comes to Vue. Any help is appreciated. Thanks!

2 Answers

Don't use submit.prevent in this scenario. Just use submit, and in your function, conditionally prevent.

onSubmit(e) {
   if(condition) e.preventDefault();
}

As Andy pointed out, @submit.prevent should not be used for conditional form submission because the .prevent modifier automatically calls Event.preventDefault().

To conditionally call it, you'd have to remove the .prevent modifier, and evaluate the htmlSubmit flag beforehand within the event handler:

<v-form @submit="onSubmit" action="https://example.com">
export default {
  methods: {
    onSubmit(e) {
      if (!this.htmlSubmit) {
        e.preventDefault() // don't perform submit action (i.e., `<form>.action`)
      }
    }
  }
}

Edit Conditional submit with v-form

Related