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('父组件已挂载')
    })
  }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM