Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue2 生命周期

作者:愛火焚城   发布日期:2025-11-12   浏览:111

// Vue 2 生命周期示例代码

new Vue({
  // 创建 Vue 实例时的选项
  el: '#app',
  data: {
    message: 'Hello Vue!'
  },
  beforeCreate() {
    console.log('beforeCreate: ', this.$el); // 此时 el 和 data 都未初始化,this.$el 为 undefined
  },
  created() {
    console.log('created: ', this.$el, this.message); // 此时 data 已经初始化,但 el 还未挂载
  },
  beforeMount() {
    console.log('beforeMount: ', this.$el); // 此时 el 已经被创建,但还未挂载到 DOM 中
  },
  mounted() {
    console.log('mounted: ', this.$el); // 此时 el 已经挂载到 DOM 中,可以操作 DOM 元素了
  },
  beforeUpdate() {
    console.log('beforeUpdate: ', this.$el, this.message); // 数据更新前的状态
  },
  updated() {
    console.log('updated: ', this.$el, this.message); // 数据更新后的状态
  },
  beforeDestroy() {
    console.log('beforeDestroy: ', this.$el); // 实例即将被销毁,还可以访问 el 和 data
  },
  destroyed() {
    console.log('destroyed: ', this.$el); // 实例已经被销毁,无法再访问 el 和 data
  }
});

<!-- HTML -->
<div id="app">
  <p>{{ message }}</p>
</div>

解释说明:

  1. beforeCreate:实例刚刚被创建,datael 都还没有初始化。
  2. created:实例已经创建完成,data 已经初始化,但 el 还没有挂载。
  3. beforeMount:模板编译完成,el 已经创建,但还未挂载到 DOM 中。
  4. mounted:实例已经挂载到 DOM 中,可以操作 DOM 元素。
  5. beforeUpdate:数据更新之前的状态。
  6. updated:数据更新之后的状态,DOM 已经更新。
  7. beforeDestroy:实例即将被销毁,还可以访问 eldata
  8. destroyed:实例已经被销毁,无法再访问 eldata

通过这些生命周期钩子函数,可以在不同的阶段执行特定的操作。

上一篇:vue for

下一篇:vue moment

大家都在看

vue.js devtools用法

vue js for循环

highlight.js vue

vue.config.js 配置

vue.config.js 配置代理

vue.config.js configu

node.js vue

vue3组件传值的方式

vue3 子路由

vue3 router传参

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站