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

vue2和vue3生命周期

作者:平凡中的不凡   发布日期:2026-06-07   浏览:91

// Vue 2 生命周期钩子示例
new Vue({
  el: '#app',
  data() {
    return {
      message: 'Hello Vue 2!'
    }
  },
  beforeCreate() {
    console.log('beforeCreate: ', this.$el); // undefined
    console.log('beforeCreate: ', this.message); // undefined
  },
  created() {
    console.log('created: ', this.$el); // undefined
    console.log('created: ', this.message); // Hello Vue 2!
  },
  beforeMount() {
    console.log('beforeMount: ', this.$el); // undefined
    console.log('beforeMount: ', document.getElementById('app').innerHTML); // {{ message }}
  },
  mounted() {
    console.log('mounted: ', this.$el); // <div id="app">Hello Vue 2!</div>
    console.log('mounted: ', document.getElementById('app').innerHTML); // Hello Vue 2!
  },
  beforeUpdate() {
    console.log('beforeUpdate');
  },
  updated() {
    console.log('updated');
  },
  beforeDestroy() {
    console.log('beforeDestroy');
  },
  destroyed() {
    console.log('destroyed');
  }
});

// Vue 3 生命周期钩子示例 (使用 Composition API)
import { createApp, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted } from 'vue';

createApp({
  setup() {
    onBeforeMount(() => {
      console.log('onBeforeMount');
    });

    onMounted(() => {
      console.log('onMounted');
    });

    onBeforeUpdate(() => {
      console.log('onBeforeUpdate');
    });

    onUpdated(() => {
      console.log('onUpdated');
    });

    onBeforeUnmount(() => {
      console.log('onBeforeUnmount');
    });

    onUnmounted(() => {
      console.log('onUnmounted');
    });

    return {
      message: 'Hello Vue 3!'
    };
  }
}).mount('#app');

解释说明:

  1. Vue 2 生命周期钩子

    • beforeCreate: 实例初始化之后,数据观测 (data observer) 和 event/watcher 事件配置之前被调用。
    • created: 实例创建完成后被调用。此时实例已完成以下的配置:数据观测 (data observer),属性和方法的运算,watch/event 事件回调。然而,挂载阶段还没开始,$el 属性目前不可见。
    • beforeMount: 在挂载开始之前被调用:相关的 render 函数首次被调用。
    • mounted: 实例挂载到 DOM 后调用。此时可以访问到真实的 DOM 元素。
    • beforeUpdate: 数据更新时调用,发生在虚拟 DOM 打补丁之前。
    • updated: 由于数据更改导致的虚拟 DOM 重新渲染和打补丁,在这之后会调用该钩子。
    • beforeDestroy: 实例销毁之前调用。实例仍然完全可用。
    • destroyed: 实例销毁后调用。此时所有的事件监听器已经被移除,所有的子实例也已经被销毁。
  2. Vue 3 生命周期钩子(Composition API)

    • onBeforeMount: 类似于 Vue 2 的 beforeMount
    • onMounted: 类似于 Vue 2 的 mounted
    • onBeforeUpdate: 类似于 Vue 2 的 beforeUpdate
    • onUpdated: 类似于 Vue 2 的 updated
    • onBeforeUnmount: 类似于 Vue 2 的 beforeDestroy
    • onUnmounted: 类似于 Vue 2 的 destroyed

这些生命周期钩子在开发中非常有用,可以帮助我们在特定的时间点执行某些操作,比如初始化数据、清理资源等。

上一篇:vue validator自定义校验

下一篇:vue 事件修饰符

大家都在看

vue.js devtools用法

three.js vue

vue js for循环

vue.min.js 本地引入

vue.js 3

highlight.js vue

vue.config.js 配置

vue.config.js 配置代理

vue.config.js devserv

vue.config.js configu

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

Laravel 中文站