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

原文地址:https://www.cnblogs.com/wuqilang/p/15110009.html