[Vuejs]-How to get a callback from event listener in Nuxt/Vue

0šŸ‘

Iā€™m not sure why you may want to notify the child. If you just want a "loading" state, a prop would do (set loading to true when axios starts and then to false when it finishes). By the way, the axios api is asyncronous (promise based), so you have to use await:

let res = await this.$axios.get(`/example/${val}`)

But going to the topic, you can call methods of the child component directly, just use ref to access the instance:

<template>
    <childcomponent ref="child" :result="result" @childEvent="handleEvent" /> 
</template>
<script>
export default {
    components:{ childcomponent },
    data(){
        return{
            result: false
        }
    }
    methods:{
        async handleEvent(val){
            let res = await this.$axios.get(`/example/${val}`)
            this.$refs.child.getResult(res)
        }
    }
}
</script>

And the child:

<template>
    <div @click="doSomething"></div>
</template>
<script>
export default {
    methods:{
        doSomething(){
            // do something
            this.$emit('childEvent', 'val')
        },
        getResult(res) {
            // do something
        }
    }
}
</script>

Leave a comment