Vue2 生命周期详解及与 Vue3 的对比

目录

Vue2 生命周期详解及与 Vue3 的对比

一、Vue2 生命周期概述

二、Vue2 生命周期中的关键阶段

1. 组件首次加载执行的生命周期

2. data 和 el 的出现阶段

3. 使用 keep-alive 增加的生命周期

三、Vue2 生命周期在面试中的常见问题

四、Vue2 与 Vue3 生命周期对比


在 Vue 开发中,生命周期是非常重要的概念。它允许我们在不同阶段执行特定的代码,从而更好地控制组件的行为。本文将详细介绍 Vue2 的生命周期,并与 Vue3 进行一些对比,同时提供相关的代码示例。

一、Vue2 生命周期概述

Vue2 版本中有八个系统自带的生命周期函数,分别是:beforeCreatecreatedbeforeMountmountedbeforeUpdateupdatedbeforeDestroydestroyed

  1. beforeCreate:在实例初始化之后,数据观测和事件配置之前被调用。此时无法访问到 datacomputed 和 watch 等属性。
  2. created:在实例创建完成后被立即调用。此时可以访问到 datacomputed 和 watch 等属性,但还未挂载到 DOM 上。
  3. beforeMount:在挂载开始之前被调用。
  4. mounted:在挂载完成后被调用。此时组件已经被渲染到 DOM 中,可以访问到 DOM 元素。
  5. beforeUpdate:数据更新时调用,发生在虚拟 DOM 重新渲染和打补丁之前。
  6. updated:由于数据更改导致的虚拟 DOM 重新渲染和打补丁之后调用。
  7. beforeDestroy:在实例销毁之前调用。在这一步,实例仍然完全可用。
  8. destroyed:在实例销毁后调用。调用后,所有的事件监听器会被移除,所有的子实例也会被销毁。

二、Vue2 生命周期中的关键阶段

1. 组件首次加载执行的生命周期

当组件首次加载时,会按照 beforeCreatecreatedbeforeMountmounted 的顺序执行前四个生命周期函数。例如:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Vue2 Lifecycle Demo</title>
  <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>

<body>
  <div id="app"></div>
  <script>
    new Vue({
      el: '#app',
      data() {
        return {
          message: 'Hello Vue2!'
        };
      },
      beforeCreate() {
        console.log('beforeCreate');
      },
      created() {
        console.log('created');
      },
      beforeMount() {
        console.log('beforeMount');
      },
      mounted() {
        console.log('mounted');
      }
    });
  </script>
</body>

</html>

2. data 和 el 的出现阶段

  • 在 created 阶段,有 data 属性,但没有 el(组件的根节点)。
  • 在 beforeMount 阶段,同样没有 el,但有 data
  • 在 mounted 阶段,既有 el 也有 data。此时组件已经被渲染到 DOM 中,可以访问到 DOM 元素。

例如,可以在代码中打印 this.$el 和 this.$data 来验证:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Vue2 Lifecycle Data and EL Demo</title>
  <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>

<body>
  <div id="app"></div>
  <script>
    new Vue({
      el: '#app',
      data() {
        return {
          itemNumber: '123'
        };
      },
      beforeCreate() {
        console.log('beforeCreate - No data or el');
      },
      created() {
        console.log('created - Has data:', this.$data.itemNumber);
        console.log('created - No el');
      },
      beforeMount() {
        console.log('beforeMount - Has data:', this.$data.itemNumber);
        console.log('beforeMount - No el');
      },
      mounted() {
        console.log('mounted - Has data:', this.$data.itemNumber);
        console.log('mounted - Has el:', this.$el);
      }
    });
  </script>
</body>

</html>

3. 使用 keep-alive 增加的生命周期

如果在 Vue2 中使用 keep-alive,会增加两个生命周期函数,分别是 activated(进入缓存的组件被激活时调用)和 deactivated(离开缓存的组件被停用时调用)。

例如:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Vue2 Lifecycle with Keep-Alive Demo</title>
  <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>

<body>
  <div id="app">
    <keep-alive>
      <component :is="currentComponent"></component>
    </keep-alive>
    <button @click="toggleComponent">Toggle Component</button>
  </div>
  <script>
    const ComponentA = {
      template: '<div>Component A</div>',
      beforeCreate() {
        console.log('Component A beforeCreate');
      },
      created() {
        console.log('Component A created');
      },
      beforeMount() {
        console.log('Component A beforeMount');
      },
      mounted() {
        console.log('Component A mounted');
      },
      activated() {
        console.log('Component A activated');
      },
      deactivated() {
        console.log('Component A deactivated');
      }
    };

    const ComponentB = {
      template: '<div>Component B</div>',
      beforeCreate() {
        console.log('Component B beforeCreate');
      },
      created() {
        console.log('Component B created');
      },
      beforeMount() {
        console.log('Component B beforeMount');
      },
      mounted() {
        console.log('Component B mounted');
      },
      activated() {
        console.log('Component B activated');
      },
      deactivated() {
        console.log('Component B deactivated');
      }
    };

    new Vue({
      el: '#app',
      data() {
        return {
          currentComponent: 'ComponentA'
        };
      },
      components: {
        ComponentA,
        ComponentB
      },
      methods: {
        toggleComponent() {
          this.currentComponent = this.currentComponent === 'ComponentA'? 'ComponentB' : 'ComponentA';
        }
      }
    });
  </script>
</body>

</html>

三、Vue2 生命周期在面试中的常见问题

在面试中,关于 Vue2 生命周期的问题可能会涉及以下几个方面:

  1. 进入组件会执行哪些生命周期?

    • 首次进入组件会执行前四个生命周期(beforeCreatecreatedbeforeMountmounted)。
    • 如果加入了 keep-alive,第一次进入组件会执行五个生命周期,即前四个加上 activated。第二次或第 N 次进入组件时,如果使用了 keep-alive,则只会执行 activated 生命周期。
  2. 在哪个阶段有 data 和 el

    • 在 created 阶段有 data,但没有 el
    • 在 mounted 阶段既有 data 也有 el
  3. 生命周期在源码中如何呈现?

    • Vue2 的生命周期函数是在源码中按照一定的顺序执行的,通过构造函数和对象的方式进行调用。例如,可以通过 new Vue() 创建实例时传入生命周期函数选项,在构造函数中执行这些函数。同时,data 和 el 的出现也是通过在不同阶段对实例属性的赋值和操作来实现的。

四、Vue2 与 Vue3 生命周期对比

Vue3 对生命周期函数进行了一些调整和优化:

  1. 命名变化:Vue3 中的生命周期函数命名更加简洁,例如 beforeCreate 改为 setup() 执行之前,created 改为 setup() 执行之后。
  2. 新增组合式 API:Vue3 引入了组合式 API,其中 setup() 函数可以替代部分传统生命周期函数的功能,并且更加灵活和易于维护。

例如,在 Vue3 中:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Vue3 Lifecycle Demo</title>
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>

<body>
  <div id="app"></div>
  <script>
    const App = {
      setup() {
        console.log('setup - Similar to beforeCreate and created');
        return {};
      },
      beforeMount() {
        console.log('beforeMount');
      },
      mounted() {
        console.log('mounted');
      }
    };

    const app = Vue.createApp(App);
    app.mount('#app');
  </script>
</body>

</html>

总的来说,了解 Vue2 的生命周期对于理解 Vue 的工作原理和进行项目开发非常重要。同时,对比 Vue2 和 Vue3 的生命周期变化,可以更好地适应新版本的开发需求。希望本文对你理解 Vue2 的生命周期有所帮助。

以上内容详细介绍了 Vue2 的生命周期,并加入了 Vue3 的对比和代码示例,可以作为一篇关于 Vue 生命周期的博客文章。在实际应用中,可以根据具体需求进一步深入研究和实践。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值