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!

2 Answers 2

5

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

onSubmit(e) {
   if(condition) e.preventDefault();
}
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.