vue面试题:生命周期场景面试

113 阅读1分钟

问题

父组件中beforCreate created beforeMount mounted四个生命周期,分别打印 1 2 3 4

子组件中beforCreate created beforeMount mounted四个生命周期,分别打印 5 6 7 8

请问父子组件的打印顺序是什么

思路

首先:父子组件中,子组件被嵌套在父组件中,是父组件的一个元素 在vue生命周期中,$el元素在mounted之后才会被打印出来 所以在beforMounte之后,就会打印子组件的生命周期, 最后打印的一个是父组件的mounted的内容 所以打印顺序应该是: 1 2 3 5 6 7 8 4

// 父组件
<template>
  <div class="hello">
    <h1>主页</h1>
    <instr></instr>
    <router-view></router-view>
    <!-- <div id="drag" v-drag>可拖拽</div> -->
  </div>
</template>

<script>
  import instr from '../instruct/index.vue'
  export default {
    name: 'HomePage',
    components: {
      instr
    },
    beforeCreate() {
      console.log(1)
    },
    created() {
      console.log(2)
    },
    beforeMount() {
      console.log(3)
    },
    mounted() {
      console.log(4)
    },
  }
</script>

--------------------------------------------------------------------------
//子组件
<template>
    <div>
        <h1>自定义指令</h1>
        <div class="drag" v-drag></div>
    </div>
</template>
<script>
    export default ({
        data() {
            return {}
        },
        beforeCreate() {
            console.log(5)
        },
        created() {
            console.log(6)
        },
        beforeMount() {
            console.log(7)
        },
        mounted() {
            console.log(8)
        },
    })
</script>

打印结果

vue父子组件生命周期打印顺序.png