vue父子组件的挂载顺序(mounted)

Father.vue:

复制代码
<script>
import Child from './Child'
export default {
  beforeCreate() {
    console.log('父组件 beforeCreate')
  },
  created() {
    console.log('父组件 created')
  },
  render() {
    console.log('父组件 render')
    return (
      <div>
        <h1>父组件</h1>
        <Child />
      </div>
    )
  },
  beforeMount() {
    console.log('父组件 beforeMount')
  },
  mounted() {
    console.log('父组件 mounted')
  },
  components: { Child }
}
</script>
<style>
div {
  text-align: center;
}
</style>
复制代码

Child.vue:

复制代码
<script>
export default {
  beforeCreate() {
    console.log('子组件 beforeCreate')
  },
  created() {
    console.log('子组件 created')
  },
  render() {
    console.log('子组件 render')
    return (
      <div>
        <h3>子组件</h3>
      </div>
    )
  },
  beforeMount() {
    console.log('子组件 beforeMount')
  },
  mounted() {
    console.log('子组件 mounted')
  }
}
</script>
复制代码

结果:父组件初始化 -> 父组件渲染完毕 -> 子组件初始化 -> 子组件挂载完毕 -> 父组件挂载完毕

子组件何时知道父组件已经挂载?

main.js:

Vue.prototype.$bus = new Vue()

Father.vue:

  mounted() {
    console.log('父组件 mounted')
    this.$bus.$emit('fatherMounted')
  }

Child.vue:

  mounted() {
    console.log('子组件 mounted')
    this.$bus.$on('fatherMounted', () => {
      console.log('父组件已挂载')
    })
  }

 

posted @   吴小明-  阅读(1847)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2020-08-06 scoped的规则
点击右上角即可分享
微信分享提示