Send data from child to parent using VueJS

Viewed 65

I'm working on a small project using Django and VueJs. Everything is good, I'd just like to know how I can send data from my component (Modal) to another one after making an Axios request? This is my code:

NB: Please read my code comments to understand what I want to do.

Child : AddContact.vue

methods: {
    post(){
        getAPI.post('api/contact/post/', this.form).then((response) => {
            // here I want to send response data to Contact.vue
        }).catch((error) => {

        })
    }
}

Parent : Contact.vue ( where I want to receive data )

<template>
   <addContactModal></addContactModal>
</template>

<script>
    import addContactModal from "../modals/contact/addContact.vue";
    import { getAPI } from '../../../vue/src/axios-api';

    export default {
        name: 'Contact',
        components: {
            addContactModal: addContactModal
        }
    };
</script>
1 Answers

You can emit a signal from the child component:

getAPI.post('api/contact/post/', this.form).then((response) => {
    this.$emit('loaded', response) // emit your signal
}).catch((error) => {
    // handle error
})

And then you bind a method of the parent to the signal. Note that:

  • the name of the signal ($emit's first arg) and the one of the @ directive must match (@ is short for v-on)
  • the second argument passed to $emit will become the first argument of the bound function
<template>
   <addContactModal @loaded="doSomethingWithResp"></addContactModal>
</template>

... 

<script>
    import addContactModal from "../modals/contact/addContact.vue";
    import { getAPI } from '../../../vue/src/axios-api';

    export default {
        name: 'Contact',
        components: {
            addContactModal: addContactModal
        },
        methods: {
            doSomethingWithResp: function (response) {
                console.log(response)
            }
        }
    };
</script>
Related