3

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!

tony19
  • 125,647
  • 18
  • 229
  • 307
Jeremy L.
  • 853
  • 8
  • 15

2 Answers2

5

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

onSubmit(e) {
   if(condition) e.preventDefault();
}
  • Thanks Andy, can you explain a bit more where exactly I'm using submit, and where you'd place this function? I'm still wrapping my head around Vue. – Jeremy L. Mar 16 '21 at 00:14
2

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

tony19
  • 125,647
  • 18
  • 229
  • 307