Vue——神秘的生命周期

从Vue的生命周期入手是尝试快速理解Vue应用的一条捷径,那么Vue在生命周期中都做了哪些操作呢?话不多说,直接上代码,感兴趣的小伙伴可以跟着敲一敲,希望直接看结论的请自行滑动至末尾。

VUE文件

<template>
    <div class="life-cycle" @click="changeMessage">
        {{message}}
    </div>
</template>
<script src="./life.js">

</script>

<style lang="less">
.life-cycle {
    position: absolute;
    top: 50%;
    left: 50%;
    
}
</style>

JS文件

export default {
  data () {
    return {
      loads: this.loadData(),
      message: 'xuxiao is boy'
    }
  },
  props: {
    pro: ['string', 'number']
  },
  methods: {
    loadData () {
      console.log('%c%s', 'color:red', 'methods   : 准备完毕,加载Data依赖')
      return 1
    },
    changeMessage () {
      this.message = 'changed message'
    }
  },
  beforeCreate: function () {
    console.log('beforeCreate 创建前状态开始===============》')
    console.table([
      ['el', `${this.$el}`],
      ['props', `${this.$props}`],
      ['data', `${this.$data}`],
      ['attrs', `${this.$attrs}`],
      ['listeners', `${this.$listeners}`],
      ['message', `${this.message}`]])
    console.log('beforeCreate 创建前状态结束===============》')
    /* console.group('beforeCreate 创建前状态===============》')
    console.log('%c%s', 'color:red', 'el     : ' + this.$el) // undefined
    console.log('%c%s', 'color:red', 'props  : ' + this.$props) // undefined
    console.log('%c%s', 'color:red', 'data   : ' + this.$data) // undefined
    console.log('%c%s', 'color:red', 'attrs   : ' + this.$attrs) // 已被初始化
    console.log('%c%s', 'color:red', 'listeners   : ' + this.$listeners) // 已被初始化
    console.log('%c%s', 'color:red', 'emit   : ' + this.$emit) // 已被初始化
    console.log('%c%s', 'color:red', 'on   : ' + this.$on) // 已被初始化
    console.log('%c%s', 'color:red', 'message: ' + this.message) */
  },
  created: function () {
    console.log('created 创建完毕状态开始===============》')
    console.table([
      ['el', `${this.$el}`],
      ['props', `${this.$props}`],
      ['data', `${this.$data}`],
      ['attrs', `${this.$attrs}`],
      ['listeners', `${this.$listeners}`],
      ['message', `${this.message}`]])
    console.log('created 创建完毕状态结束===============》')
    /* console.group('created 创建完毕状态===============》')
    console.log('%c%s', 'color:red', 'el     : ' + this.$el) // undefined
    console.log('%c%s', 'color:red', 'props  : ' + this.$props) // 已被初始化
    console.log('%c%s', 'color:red', 'data   : ' + this.$data) // 已被初始化
    console.log('%c%s', 'color:red', 'attrs   : ' + this.$attrs) // 已被初始化
    console.log('%c%s', 'color:red', 'listeners   : ' + this.$listeners) // 已被初始化
    console.log('%c%s', 'color:red', 'message: ' + this.message) // 已被初始化 */
  },
  beforeMount: function () {
    console.log('beforeMount 挂载前状态开始===============》')
    console.table([
      ['el', `${this.$el}`],
      ['props', `${this.$props}`],
      ['data', `${this.$data}`],
      ['attrs', `${this.$attrs}`],
      ['listeners', `${this.$listeners}`],
      ['message', `${this.message}`]])
    console.log('beforeMount 挂载前状态结束===============》')
    /* console.group('beforeMount 挂载前状态===============》')
    console.log('%c%s', 'color:red', 'el     : ' + (this.$el)) // 已被初始化
    console.log('%c%s', 'color:red', 'props  : ' + this.$props) // 已被初始化
    console.log(this.$el)
    console.log('%c%s', 'color:red', 'data   : ' + this.$data) // 已被初始化
    console.log('%c%s', 'color:red', 'attrs   : ' + this.$attrs) // 已被初始化
    console.log('%c%s', 'color:red', 'listeners   : ' + this.$listeners) // 已被初始化
    console.log('%c%s', 'color:red', 'message: ' + this.message) // 已被初始化 */
  },
  mounted: function () {
    console.log('mounted 挂载结束状态开始===============》')
    console.table([
      ['el', `${this.$el}`],
      ['props', `${this.$props}`],
      ['data', `${this.$data}`],
      ['attrs', `${this.$attrs}`],
      ['listeners', `${this.$listeners}`],
      ['message', `${this.message}`]])
    console.log('mounted 挂载结束状态结束===============》')
    /* console.group('mounted 挂载结束状态===============》')
    console.log('%c%s', 'color:red', 'el     : ' + this.$el) // 已被初始化
    console.log('%c%s', 'color:red', 'props  : ' + this.$props) // 已被初始化
    console.log(this.$el)
    console.log('%c%s', 'color:red', 'data   : ' + this.$data) // 已被初始化
    console.log('%c%s', 'color:red', 'attrs   : ' + this.$attrs) // 已被初始化
    console.log('%c%s', 'color:red', 'listeners   : ' + this.$listeners) // 已被初始化
    console.log('%c%s', 'color:red', 'message: ' + this.message) // 已被初始化 */
  },
  beforeUpdate: function () {
    console.log('beforeUpdate 更新前状态开始===============》')
    console.table([
      ['el', `${this.$el.innerHTML}`],
      ['props', `${this.$props}`],
      ['data', `${JSON.stringify(this.$data)}`],
      ['attrs', `${this.$attrs}`],
      ['listeners', `${this.$listeners}`],
      ['message', `${this.message}`]])
    console.log('beforeUpdate 更新前状态结束===============》')
    /* console.group('beforeUpdate 更新前状态===============》')
    console.log('%c%s', 'color:red', 'el     : ' + this.$el.innerHTML)
    console.log(this.$el)
    console.log('%c%s', 'color:red', 'data   : ' + JSON.stringify(this.$data))
    console.log('%c%s', 'color:red', 'message: ' + this.message)
    console.groupEnd() */
  },
  updated: function () {
    console.log('updated 更新完成状态开始===============》')
    console.table([
      ['el', `${this.$el.innerHTML}`],
      ['props', `${this.$props}`],
      ['data', `${JSON.stringify(this.$data)}`],
      ['attrs', `${this.$attrs}`],
      ['listeners', `${this.$listeners}`],
      ['message', `${this.message}`]])
    console.log('updated 更新完成状态结束===============》')
    /* console.group('updated 更新完成状态===============》')
    console.log('%c%s', 'color:red', 'el     : ' + this.$el.innerHTML)
    console.log(this.$el)
    console.log('%c%s', 'color:red', 'data   : ' + JSON.stringify(this.$data))
    console.log('%c%s', 'color:red', 'message: ' + this.message)
    console.groupEnd() */
  },
  beforeDestroy: function () {
    console.log('beforeDestroy 销毁前状态开始===============》')
    console.table([
      ['el', `${this.$el}`],
      ['props', `${this.$props}`],
      ['data', `${this.$data}`],
      ['attrs', `${this.$attrs}`],
      ['listeners', `${this.$listeners}`],
      ['message', `${this.message}`]])
    console.log('beforeDestroy 销毁前状态结束===============》')
    /* console.group('beforeDestroy 销毁前状态===============》')
    console.log('%c%s', 'color:red', 'el     : ' + this.$el)
    console.log(this.$el)
    console.log('%c%s', 'color:red', 'data   : ' + this.$data)
    console.log('%c%s', 'color:red', 'message: ' + this.message) */
  },
  destroyed: function () {
    console.log('destroyed 销毁完成状态开始===============》')
    console.table([
      ['el', `${this.$el}`],
      ['props', `${this.$props}`],
      ['data', `${this.$data}`],
      ['attrs', `${this.$attrs}`],
      ['listeners', `${this.$listeners}`],
      ['message', `${this.message}`]])
    console.log('destroyed 销毁完成状态结束===============》')
    /* console.group('destroyed 销毁完成状态===============》')
    console.log('%c%s', 'color:red', 'el     : ' + this.$el)
    console.log(this.$el)
    console.log('%c%s', 'color:red', 'data   : ' + this.$data)
    console.log('%c%s', 'color:red', 'message: ' + this.message) */
  }
}

说明,JS文件中有两种查看方式,个人感觉table更加直观,喜欢用group的小伙伴请自行切换

console结果

133961530798781_.pic_hd

结论:

1、 a t t r s 、 attrs、 attrslisteners会在beforeCreate中准备好
2、methods中的函数会在beforeCreate之后created之前准备好
3、data和props会在created中准备好
4、在mounted中$el才会定义
5、在beforeUpdate中data已经更新但是$el还没有
### Vue 3 生命周期钩子详解 Vue 3 提供了一组生命周期钩子,用于在组件的不同阶段执行特定的逻辑。这些钩子可以帮助开发者更好地控制组件的行为和状态变化过程。 #### 组件生命周期概述 Vue 3 的生命周期分为几个主要阶段:创建、挂载、更新和卸载。每个阶段都有相应的钩子函数可供使用[^2]。以下是详细的生命周期钩子列表: 1. **`beforeCreate`** - 在实例初始化之后立即调用。 - 此时,响应式数据尚未设置完成,无法访问 `data` 或者 `methods` 属性。 2. **`created`** - 在实例创建完成后调用。 - 可以在此处访问并操作 `data` 和 `methods`,但此时 DOM 尚未生成。 3. **`beforeMount`** - 在挂载开始之前调用。 - 此时模板已经编译完毕,但还未挂载到页面上。 4. **`mounted`** - 当组件被成功挂载到 DOM 上后调用。 - 是发起 AJAX 请求或者操作真实 DOM 的理想时机。 5. **`beforeUpdate`** - 数据发生变化时触发,在虚拟 DOM 更新前调用。 - 可以用来捕获即将发生的变化。 6. **`updated`** - 虚拟 DOM 完成更新后调用。 - 不建议在这里修改数据,因为可能会引发无限循环。 7. **`beforeUnmount` (原 `beforeDestroy`)** - 即将销毁组件时调用。 - 可以在此清理定时器或其他资源。 8. **`unmounted` (原 `destroyed`)** - 组件完全销毁后调用。 - 所有的事件监听器和子组件都会自动解除绑定。 --- #### 使用方法 ##### Options API 方式 这是传统的声明周期钩子写法,类似于 Vue 2 的风格。例如: ```javascript export default { data() { return { message: 'Hello Vue!' }; }, beforeCreate() { console.log('Before Create'); }, created() { console.log('Created', this.message); }, mounted() { console.log('Mounted'); } }; ``` ##### Composition API 方式 Composition API 引入了新的生命周期注册方式——通过 `onXXX` 方法导入并使用。这种方式更灵活且适合复杂业务逻辑拆分。例如: ```javascript import { ref, onMounted, onUpdated, onUnmounted } from 'vue'; export default { setup() { const count = ref(0); onMounted(() => { console.log('Component has been mounted!'); }); onUpdated(() => { console.log(`Count updated to ${count.value}`); }); onUnmounted(() => { console.log('Component will be unmounted.'); }); return { count }; } }; ``` --- #### 钩子的具体应用场景 - **`beforeCreate`/`created`**: 初始化外部库、订阅消息总线或加载初始数据。 - **`beforeMount`/`mounted`**: 操作真实的 DOM 元素,比如动态调整样式或尺寸;也可以发送网络请求获取数据。 - **`beforeUpdate`/`updated`**: 对比前后差异来决定是否需要进一步处理某些情况下的视图同步问题。 - **`beforeUnmount`/`unmounted`**: 清理不必要的副作用,如清除计时器、取消订阅等防止内存泄漏。 --- ### 总结 Vue 3 的生命周期设计既保留了经典选项式的简单易懂特性,又新增加了基于组合模式的支持,使得代码结构更加清晰合理[^4]。无论是初学者还是资深工程师都能找到适合自己项目需求的最佳实践方案。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值