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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><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>
</code>
<code><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> </code>
<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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><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>
</code>
<code><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> </code>
<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>

3

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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> props: {
form: Object,
isEditing: Boolean,
},
emits: ['submit', 'update:isEditing']
</code>
<code> props: { form: Object, isEditing: Boolean, }, emits: ['submit', 'update:isEditing'] </code>
  props: {
    form: Object,
    isEditing: Boolean,
  },
  emits: ['submit', 'update:isEditing']

And use prevent modifier:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><form @submit.prevent="handleSubmit">
</code>
<code><form @submit.prevent="handleSubmit"> </code>
<form @submit.prevent="handleSubmit">

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật