node.jsformsvue.jsevents

Vue 3: Prevent Redundant Form Submissions When Resetting State Between Parent and Child Components


Issue: In a Vue 3 application, form submissions are being redundantly triggered. This happens even though @submit.prevent and event.stopPropagation() are used. The issue seems linked to the resetForm method, which is called after form submission to reset the state. Both AdminBookForm and AdminBook components manage the form state and interact via props and events.

Steps to Reproduce:

  1. A form object is passed as a prop from AdminBook to AdminBookForm.
  2. The handleSubmit method in AdminBookForm emits a submit event.
  3. The parent AdminBook handles the submit event, processes the form, and calls its own resetForm method.
  4. Resetting the form (or something) triggers another submission. (console.logs confirm this).

Question: How can I prevent redundant submissions caused by resetting the form state? Is the interaction between the parent and child components (prop-watching and event-emitting) causing this issue, and how can it be improved?

(Note: this code "seems" to work now - stopping the double submission, but I don't understand why it was double submitting, and how I can avoid that without having to put all the submit.prevent and the event.stopPropogation crap in there (unless it is good and necessary crap).)

I've also been a lazy coder and been getting aid from CoPilot and chatgpt on this. Perhaps it is suggesting an improper way to pass the events from child to parent that I shouldn't be doing.

AdminBookForm.vue

<template>
  <div>
    <form ref="bookForm" @submit.prevent="handleSubmit">
      <input type="text" v-model="localForm.title" placeholder="Title" required />
      <input type="text" v-model="localForm.author" placeholder="Author" />
      <button type="submit">Submit</button>
      <button type="button" @click="resetForm">Reset</button>
    </form>
  </div>
</template>

<script>
export default {
  props: {
    form: Object,
    isEditing: Boolean,
  },
  data() {
    return {
      localForm: { ...this.form },
    };
  },
  watch: {
    form: {
      handler(newVal) {
        this.localForm = { ...newVal };
      },
      deep: true,
    },
  },
  methods: {
    handleSubmit(event) {
      if (event) event.stopPropagation();
      this.$emit('submit', { form: this.localForm, isEditing: this.isEditing });
    },
    resetForm() {
      console.log('resetForm called');
      this.localForm = { title: '', author: '' }; // Reset the form state
      this.$emit('update:isEditing', false); // Notify parent that editing has stopped
    },
  },
};
</script>

AdminBook.vue

<template>
  <div>
    <AdminBookForm
      :form="form"
      :isEditing="isEditing"
      @submit="handleSubmit"
      @update:isEditing="updateIsEditing"
    />
  </div>
</template>

<script>
import AdminBookForm from './AdminBookForm.vue';

export default {
  components: { AdminBookForm },
  data() {
    return {
      form: { title: '', author: '' },
      isEditing: false,
    };
  },
  methods: {
    async handleSubmit({ form, isEditing }) {
      if (!form) {
        console.warn('Invalid form submission');
        return;
      }
      console.log('Form submitted:', form, isEditing);
      // Simulate form processing
      await this.processForm(form);

      // Reset the form in the parent after submission
      this.resetForm();
    },
    resetForm() {
      console.log('Parent resetForm called');
      this.form = { title: '', author: '' }; // Reset parent state
      this.isEditing = false;
    },
    updateIsEditing(newVal) {
      this.isEditing = newVal;
    },
    async processForm(form) {
      // Simulate async processing
      console.log('Processing form:', form);
      return new Promise((resolve) => setTimeout(resolve, 1000));
    },
  },
};
</script>

Solution

  • event.preventDefault() (prevent modifier) and event.stopPropogation() (stop modifier) serve different purposes. The former prevents default behaviour of form element (GET request is sent on submit), the latter prevents submit event from being propagated through DOM (and received by other elements). It can be shortened to @submit.stop.prevent="handleSubmit", but this is not necessary in this case.

    The problem here is that parent component uses the same event name (submit), and Vue events and DOM events aren't distinguished. So handleSubmit receives both Vue event object and DOM submit event object where event.form doesn't exist. The way to avoid this is to declare expected Vue events in child component:

      props: {
        form: Object,
        isEditing: Boolean,
      },
      emits: ['submit', 'update:isEditing']
    

    And use prevent modifier:

    <form @submit.prevent="handleSubmit">