Home > Mobile >  Submit a form and fire parent method when child emitted event is received in Vue 2
Submit a form and fire parent method when child emitted event is received in Vue 2

Time:02-25

I have a parent container of App.vue. In App.vue I have a <form></form>. Inside of that form I have a child component. Within the child I am using a custom button component. App.vue --> Parent UserInfo.vue --> Child BaseButton.vue --> Child within User.Info.vue

In UserInfo.vue I use the BaseButton like so:

<base-button @click="sendData" />

UserInfo -> sendData()

sendData() {
  console.log('here')
  this.$emit('send-data-to-parent');
},

Form in App.vue

 <form @send-data-to-parent="submitThisForm">
    <user-info/>
 </form>

submitThisForm()

 submitThisForm() {
      console.log('test')
    }

When I click the button I see the console.log('here') in the console but I am not seeing the console.log('test') from the App.vue submitThisForm() method.

Why is this?

CodePudding user response:

@send-data-to-parent="submitThisForm"

is on your form element. Try to put in to the component, like:

 <form>
    <user-info @send-data-to-parent="submitThisForm"/>
 </form>

Working example:

https://codesandbox.io/s/condescending-panna-sxx6k3?file=/src/components/Parent.vue

  • Related