如何知道子组件是从哪个组件调用的?

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

我正在使用 vuex 进行集中状态管理

我会尽量解释我的问题。

我有两个组件 componentAcomponentB

组件B

<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 存在于 componentA 中,如下所示:

<template>

    <componentB></componentB>

</template>

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

整个组合组件即 componentBcomponentA 中被视为单个组件是可重用的。

所以我在其他各种组件中使用这个组合的可重用组件如下:

组件 1

  <template>

    <componentA></componentA>

</template>

分量 2

  <template>

    <componentA></componentA>

</template>

分量 3

  <template>

    <componentA></componentA>

</template> 

所以我的问题是我如何知道 componentBcreated() 生命周期挂钩是从哪个组件调用的,以便我可以执行适当的功能。

您可以这样找到父组件:this.$parent

如果您需要找到 2 层深的父级,请请求更深的父级:this.$parent.$parent(注意,根实例显然没有父级)。

您的问题示例:

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>