Vue父子组件的生命周期执行顺序
    		       		warning:
    		            这篇文章距离上次修改已过436天,其中的内容可能已经有所变动。
    		        
        		                
                在Vue中,父子组件的生命周期执行顺序遵循以下规则:
- 父组件 beforeCreate
- 父组件 created
- 父组件 beforeMount
- 子组件 beforeCreate
- 子组件 created
- 子组件 beforeMount
- 子组件 mounted
- 父组件 mounted
更新过程中:
- 父组件 beforeUpdate
- 子组件 beforeUpdate
- 子组件 updated
- 父组件 updated
销毁过程中:
- 父组件 beforeDestroy
- 子组件 beforeDestroy
- 子组件 destroyed
- 父组件 destroyed
这里是一个简单的例子来展示这些生命周期钩子的执行顺序:
<template>
  <div>
    <parent-component></parent-component>
  </div>
</template>
 
<script>
import ParentComponent from './components/ParentComponent.vue';
 
export default {
  components: {
    ParentComponent
  }
}
</script>父组件 (ParentComponent.vue):
<template>
  <div>
    <child-component></child-component>
  </div>
</template>
 
<script>
import ChildComponent from './ChildComponent.vue';
 
export default {
  components: {
    ChildComponent
  },
  beforeCreate() {
    console.log('父组件 beforeCreate');
  },
  created() {
    console.log('父组件 created');
  },
  beforeMount() {
    console.log('父组件 beforeMount');
  },
  mounted() {
    console.log('父组件 mounted');
  },
  beforeUpdate() {
    console.log('父组件 beforeUpdate');
  },
  updated() {
    console.log('父组件 updated');
  },
  beforeDestroy() {
    console.log('父组件 beforeDestroy');
  },
  destroyed() {
    console.log('父组件 destroyed');
  }
}
</script>子组件 (ChildComponent.vue):
<template>
  <div>Child Component</div>
</template>
 
<script>
export default {
  beforeCreate() {
    console.log('子组件 beforeCreate');
  },
  created() {
    console.log('子组件 created');
  },
  beforeMount() {
    console.log('子组件 beforeMount');
  },
  mounted() {
    console.log('子组件 mounted');
  },
  beforeUpdate() {
    console.log('子组件 beforeUpdate');
  },
  updated() {
    console.log('子组件 updated');
  },
  beforeDestroy() {
    console.log('子组件 beforeDestroy');
  },
  destroyed() {
    console.log('子组件 destroyed');
  }
}
</script>当你运行这些组件时,你会在控制台看到上述生命周期钩子的执行顺序。
评论已关闭