JavaScriptVue js

Vue-Emit data from child to parent in vue js

In this article, we will learn about how to emit data from child to parent in VueJS with the example, I will show you an example that how we can pass child data to our parent component,
We will use emit method to pass the data from the child component to the parent component in vuejs.

Let’s suppose my child component name as Child.vue and have the below code into it.

<template>
    <div>
        <b-tabs v-model="selectedTab" vertical content-class="col-12 col-md-9 mt-1 mt-md-0" pills nav-wrapper-class="col-md-3 col-12"
            nav-class="nav-left">
            <!-- general tab -->
            <b-tab active @click="getSelectedTab('general')">
                <!-- title -->
                <template #title>
                    <feather-icon icon="UserIcon" size="18" class="mr-50" />
                    <span class="font-weight-bold">General</span>
                </template>
                <profile v-if="options.info" :information-data="options.info" />
            </b-tab>
        </b-tabs>
    </div>
</template>
<script> 
    export default { 
        methods:{
            getSelectedTab(tabName){
                this.$emit('get-tab-name', tabName);
              
            }
        }
    }
</script>

In this code I have a tab component, on the tab select I will call the getSelectedTab method and as parameter tabName I am passing the selected tab name. Now We will see how we can get the value in Parent.vue component.

Parent.vue Component

<template>
    <div>
        <account @get-tab-name= 'getTabName'></account>
    </div>
</template>
<script>
import Account from '../Account.vue'
    export default {
        methods: {
            getTabName(tabName) {
                console.log(tabName);
            }
        },
    }

</script>

Now in this Parent.vue component first I have imported the account component then you can I have passed here as @get-tab-name this is the same name which I have added in the emit.

Now, whenever my child component function is called we get our value in our parent component inside our getTabName function.

I hope you understood how we can use emit to pass data from the child to parent component. Rate me 5 so that I will be motivated. Thanks for visiting my website.

Shaiv Roy

Hy Myself shaiv roy, I am a passionate blogger and love to share ideas among people, I am having good experience with laravel, vue js, react, flutter and doing website and app development work from last 7 years.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button