I need to handle an event in a child component; check for a certain condition; if true, emit the "submit" event back to the parent so it's event handler will run.
The example below fires the parent's event handler once using Vue.js 2.6.11 (replacing "vue" with "@vue/composition-api"). With 3.0.0-rc.5, it fires twice. Wondering if this is an intentional change, a bug, or me.
App.vue:
<template lang="pug">
#app
.container
h1 Form Experiment
FormGroup(@submit='onSubmit')
button.btn.btn-primary(type='submit') Submit
</template>
<script lang="ts">
import { defineComponent } from "vue"
import FormGroup from "@/components/FormGroup.vue"
export default defineComponent({
name: "App",
components: {
FormGroup,
},
setup() {
const onSubmit = (): void => {
alert("Parent event handler")
}
return { onSubmit }
}
})
</script>
FormGroup.vue:
<template lang="pug">
form(@submit.prevent='onFormSubmit', novalidate, autocomplete='on')
slot Content needed in FormGroup
</template>
<script lang="ts">
import { defineComponent } from "vue"
export default defineComponent({
name: "FormGroup",
setup(_, { emit }) {
const check = ref(true) // evaluated elsewhere - simplified for this example
const onFormSubmit = (): void => {
if (check.value) {
alert("Form is valid - sending event to parent")
emit("submit")
} else {
alert("Form is not valid.") // so don't emit the event to parent
}
}
return { check, onFormSubmit }
}
})
</script>
Any thoughts regarding why onSubmit() in the parent fires twice in Vue.js 3.0.0-rc.5?
<form>being the root element? I'd be curious if the same thing happened if FormGroup was rooted as a<div><form...instead@vue/composition-api, and it also fires twice, so I don't think this is a bug in Vue 3. Daniel's answer should provide a solution.