Vue 生命周期解析

目录

Vue 生命周期解析

一、Vue2 生命周期回顾

二、Vue2 生命周期实现原理

三、Vue3 中的生命周期变化

四、代码示例


在 Vue 的开发中,生命周期是一个非常重要的概念。本文将结合视频内容,对 Vue2 的生命周期进行详细分析,并探讨在加入 Vue3 以及代码示例的情况下,生命周期的变化。

一、Vue2 生命周期回顾

  1. 生命周期函数数量:Vue2 中系统自带的生命周期一共有八个,分别为beforeCreatecreatedbeforeMountmountedbeforeUpdateupdatedbeforeDestroydestroyed
  2. 执行顺序:在 Vue2 中,生命周期函数的执行顺序是固定的,即使在代码中打乱顺序,实际执行时也会按照既定的顺序进行。例如,在组件执行时,会先执行前四个生命周期函数,即beforeCreatecreatedbeforeMountmounted
  3. 数据与节点的出现时机
    • beforeCreate阶段,this.$datathis.$el都为undefined
    • created阶段,有了this.$data,但this.$el仍为undefined
    • mounted阶段,既有this.$data,又有this.$el

二、Vue2 生命周期实现原理

在 Vue2 的源码底层,已经写好了生命周期函数的执行顺序。通过判断传入的选项对象中的函数类型,依次执行对应的生命周期函数。例如:

if (typeof options.beforeCreate === 'function') {
  options.beforeCreate();
}
// 以此类推执行其他生命周期函数

三、Vue3 中的生命周期变化

在 Vue3 中,生命周期函数的名称发生了一些变化:

  • beforeCreate改为setup之前执行的代码。
  • created改为setup内部执行的代码,并且可以使用refreactive来定义响应式数据。
  • beforeMountmounted基本保持不变。
  • beforeUpdateupdated也基本保持不变。
  • beforeDestroy改为onBeforeUnmount
  • destroyed改为onUnmounted

四、代码示例

以下是一个 Vue2 的简单组件示例,展示了生命周期函数的使用:

<!DOCTYPE html>
<html>

<head>
  <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>

<body>
  <div id="app">
    {{ message }}
  </div>
  <script>
    new Vue({
      el: '#app',
      data: {
        message: 'Hello Vue!'
      },
      beforeCreate() {
        console.log('beforeCreate');
      },
      created() {
        console.log('created');
      },
      beforeMount() {
        console.log('beforeMount');
      },
      mounted() {
        console.log('mounted');
      },
      // 其他生命周期函数...
    });
  </script>
</body>

</html>

在 Vue3 中,可以使用组合式 API 来定义组件,以下是一个示例:

<!DOCTYPE html>
<html>

<head>
  <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');
        const message = ref('Hello Vue3!');
        return {
          message
        };
      },
      onBeforeMount() {
        console.log('onBeforeMount');
      },
      onMounted() {
        console.log('onMounted');
      }
      // 其他生命周期函数...
    };
    const app = Vue.createApp(App);
    app.mount('#app');
  </script>
</body>

</html>

通过以上内容,相信大家对 Vue 的生命周期有了更深入的理解。无论是 Vue2 还是 Vue3,生命周期函数都在组件的不同阶段发挥着重要作用,帮助开发者更好地管理组件的状态和行为。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值