Vue 的父、子组件生命周期钩子函数执行顺序

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第 3 天,点击查看活动详情

Vue 中父、子组件生命周期钩子函数执行顺序可以分为以下几种:

// Parent.vue
<template>
  <div>
    parent
    <div>{{ parentContent }}</div>
    <button @click="handleModify">修改</button>
    <button @click="handleDestroyed">销毁父组件</button>
    <Child></Child>
  </div>
</template>

<script>
import Child from './child'

export default {
  name: 'Parent',
  components: {
    Child
  },
  data () {
    return {
      parentContent: '父组件内容'
    }
  },
  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')
  },
  methods: {
    handleModify(){
      this.parentContent = '更改后的内容'
    },
    handleDestroyed(){
      this.$destroy()
    }
  }
}
</script>
复制代码
// Child.vue
<template>
  <div>
    child
    <div>{{ childContent }}</div>
    <button @click="modifyClild">修改</button>
    <button @click="handleDestroyed">销毁子组件</button>
  </div>
</template>

<script>
export default {
  name: 'Child',
  data () {
    return {
      childContent: '子组件内容'
    }
  },
  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')
  },
  methods:{
    modifyClild() {
      this.childContent = '更改后的子组件内容'
    },
    handleDestroyed(){
      this.$destroy()
    }
  }
}
</script>
复制代码
1. 加载渲染过程
父 beforeCreate() -> 父 created() -> 父 beforeMount() -> 子 beforeCreate() -> 子 created() -> 子 beforeMount() -> 子 mounted() -> 父 mounted() 
复制代码
<div>
  parent
  <Child></Child>
</div>
复制代码

image.png

2. 父组件更新过程
父 beforeUpdate() -> 父 Updated()
复制代码

image.png

3. 子组件更新过程
父 beforeUpdate() -> 子 beforeUpdate() -> 子 Updated() -> 父 Updated()
复制代码
4. 父组件销毁过程
父 beforeDestroy() -> 子 beforeDestroy() -> 子 destroyed() -> 父 destroyed()
复制代码

image.png

5. 子组件销毁过程
子 beforeDestroy() -> 子 destroyed()
复制代码

image.png

猜你喜欢

转载自juejin.im/post/7109308586274078751