Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know from which component is the child component called from?

I am using vuex for centeralized state management

I will try explaining my problem as easily understandable as possible.

I have two components componentA and componentB.

componentB

<template>
    <p>{{ value }}</p>
</template>

<script>
    export default{
        data(){
            return{
                value: ''
            };
        },
        created(){
            if(called from component 1){
                this.value = 'called from component 1';
            }else if(called from component 2){
                this.value = 'called from component 2';
            }else if(called from component 3){
                this.value = 'called from component 3';
            }else{
                this.value = 'called from default component';
            }
        }
    }
</script>

componentB is present inside componentA as follows:

<template>

    <componentB></componentB>

</template>

<script>
    // import for componentB.
    export default{
        components:{
            'componentB': componentB
        }
    }
</script>

This whole combined component i.e componentB inside componentA considered as single component is reusable.

So I use this combined reuseable component in various other components as follows:

component 1

  <template>

    <componentA></componentA>

</template>

component 2

  <template>

    <componentA></componentA>

</template>

component 3

  <template>

    <componentA></componentA>

</template> 

so my problem is how can I know from which component was created() lifecycle hook of componentB called so that I can execute the appropriate functionality.

  • I can think of using props but I have to pass the prop two levels deep everytime

  • or Is there any better approach?

like image 220
Vamsi Krishna Avatar asked Dec 03 '25 04:12

Vamsi Krishna


1 Answers

You can find parent component like this: this.$parent.

If you need to find parent 2 levels deep, request deeper parent: this.$parent.$parent (note, that root instance has no parent obviously).

Example for your question:

Vue.component('component-b', {
  template: `<div>I'm component-b</div>`,
  mounted() {
    // log parent tag 2 levels up:
  	console.log('called by: ', this.$parent.$parent.$vnode.tag)
  }
});

// calls B
Vue.component('component-a', {
  template: `<div>I'm component-a
  	<component-b></component-b>
  	</div>`
});

// this is the top component, calls A
Vue.component('component-top', {
  template: `<div><component-a></component-a></div>`,
});

new Vue({
  el: '#app'
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="app">
  <component-top></component-top>
</div>
like image 175
Egor Stambakio Avatar answered Dec 05 '25 19:12

Egor Stambakio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!