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