vue 父子组件加载生命周期

这篇文章展示了Vue.js组件的生命周期,从父组件到子组件的初始化、挂载、更新和销毁过程。通过在不同生命周期钩子函数中打印日志,可以清晰看到beforeCreate、created、beforeMount、mounted、beforeUpdate、updated、beforeDestroy和destroyed等阶段的执行顺序。当点击按钮改变状态时,会触发组件的更新和销毁操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

初始化执行顺序:
在这里插入图片描述
卸载顺序:
在这里插入图片描述
挂载顺序:
在这里插入图片描述

类似于洋葱数据模型

<template>
  <div>
    {{ count }}
    <button @click="changeCount">change count</button>
    <button @click="changeIsShow">change isShow</button>
    <ChildrenDemo v-if="isShow"></ChildrenDemo>
  </div>
</template>

<script>
  const ChildrenDemo = {
    template: `
    <div>
        <div>{{count2}}</div>
        <button @click="changeCount2">change count2</button>
      </div>`,
    name: 'Children',
    data() {
      return {
        count2: 1,
      }
    },
    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: {
      changeCount2() {
        this.count2++
      },
    },
  }
  export default {
    components: {
      ChildrenDemo,
    },
    data() {
      return {
        count: 0,
        isShow: true,
      }
    },
    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: {
      changeCount() {
        this.count++
      },
      changeIsShow() {
        this.isShow = !this.isShow
      },
    },
  }
</script>

<style lang="scss" scoped></style>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值