Vue 中父组件怎么监听到子组件的生命周期?

背景:
在 Vue中,父组件不能直接监听子组件的生命周期钩子,然而可以实现父组件对子组件生命周期的间接监听或执行特定操作。

方法一:通过事件通信

子组件在生命周期中触发自定义事件,父组件监听这些事件。

  1. 子组件
<template>
  <div>子组件</div>
</template>

<script>
export default {
  name: 'ChildComponent',
  mounted() {
    this.$emit('childMounted');
  }
}
</script>
  1. 父组件
<template>
  <div>
    <ChildComponent @childMounted="handleChildMounted" />
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  },
  methods: {
    handleChildMounted() {
      console.log('子组件已挂载');
    }
  }
}
</script>

方法二:使用 ref

父组件通过 ref 直接访问子组件实例,并在父组件的生命周期钩子中调用子组件的方法。

  1. 子组件
<template>
  <div>子组件</div>
</template>

<script>
export default {
  name: 'ChildComponent',
  mounted() {
    console.log('子组件已挂载');
  }
}
</script>
  1. 父组件
<template>
  <div>
    <ChildComponent ref="child" />
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  },
  mounted() {
    this.$refs.child.$on('hook:mounted', this.handleChildMounted);
  },
  methods: {
    handleChildMounted() {
      console.log('通过 ref 获取子组件的挂载');
    }
  }
}
</script>

方法三:使用 provide 和 inject

通过 provide 和 inject 实现跨层级组件通信。

  1. 子组件
<template>
  <div>子组件</div>
</template>

<script>
export default {
  name: 'ChildComponent',
  inject: ['notifyParent'],
  mounted() {
    this.notifyParent('mounted');
  }
}
</script>
  1. 父组件
<template>
  <div>
    <ChildComponent />
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  },
  provide() {
    return {
      notifyParent: this.handleNotification
    }
  },
  methods: {
    handleNotification(hook) {
      if (hook === 'mounted') {
        console.log('子组件已挂载');
      }
    }
  }
}
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值