Vue3生命周期 VS Vue2生命周期(小记)

概念:Vue组件实例在创建时要经历一系列的初始化步骤,在此过程中Vue会在合适的时机,调用特定的函数,从而让开发者有机会在特定阶段运行自己的代码,这些特定的函数统称为:生命周期钩子。

  • 规律:

    生命周期整体分为四个阶段,分别是:创建、挂载、更新、销毁,每个阶段都有两个钩子,一前一后。

  • Vue2的生命周期

    创建阶段:beforeCreatecreated

    挂载阶段:beforeMountmounted

    更新阶段:beforeUpdateupdated

    销毁阶段:beforeDestroydestroyed

  • Vue3的生命周期

    创建阶段:setup

    挂载阶段:onBeforeMountonMounted

    更新阶段:onBeforeUpdateonUpdated

    卸载阶段:onBeforeUnmountonUnmounted

  • 常用的钩子:onMounted(挂载完毕)、onUpdated(更新完毕)、onBeforeUnmount(卸载之前)

  • 示例代码:

<template>
  <div class="person">
    <h2>当前求和为:{
  { sum }}</h2>
    <button @click="changeSum">点我sum+1</button>
  </div>
</template>

<!-- vue3写法 -->
<script lang="ts" setup name="Person">
  import { 
    ref, 
    onBeforeMount, 
    onMounted, 
    onBeforeUpdate, 
    onUpdated, 
    onBeforeUnmount, 
    onUnmounted 
  } from 'vue'

  // 数据
  let sum = ref(0)
  // 方法
  function changeSum() {
    sum.value += 1
  }
  console.log('setup')
  // 生命周期钩子
  onBeforeMount(()=>{
    console.log('挂载之前')
  })
  onMounted(()=>{
    console.log('挂载完毕')
  })
  onBeforeUpdate(()=>{
    console.log('更新之前')
  })
  onUpdated(()=>{
    console.log('更新完毕')
  })
  onBeforeUnmount(()=>{
    console.log('卸载之前')
  })
  onUnmounted(()=>{
    console.log('卸载完毕')
  })
</script>

相关推荐

  1. Vue3生命周期 VS Vue2生命周期(小记)

    2024-01-27 19:28:05       38 阅读
  2. Vue3生命周期Vue2生命周期对比

    2024-01-27 19:28:05       39 阅读
  3. vue3生命周期

    2024-01-27 19:28:05       4 阅读
  4. Vue2生命周期

    2024-01-27 19:28:05       16 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-27 19:28:05       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-27 19:28:05       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-27 19:28:05       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-27 19:28:05       18 阅读

热门阅读

  1. 【leetcode100-063到068】【二分】六题合集

    2024-01-27 19:28:05       31 阅读
  2. 【C语言】(4)数组

    2024-01-27 19:28:05       32 阅读
  3. MySQL数据库备份的相关命令-运维面试常问

    2024-01-27 19:28:05       29 阅读
  4. SQL 优化建议

    2024-01-27 19:28:05       29 阅读
  5. MySQL运维实战(4.8) SQL_MODE之NO_ENGINE_SUBSTITUTION

    2024-01-27 19:28:05       30 阅读
  6. 使用scyllaDb 或者cassandra存储聊天记录

    2024-01-27 19:28:05       32 阅读
  7. 天梯赛 L3-020 至多删三个字符

    2024-01-27 19:28:05       36 阅读
  8. 《动手学深度学习(PyTorch版)》笔记4.2 4.3

    2024-01-27 19:28:05       34 阅读
  9. Implement Trie (Prefix Tree)

    2024-01-27 19:28:05       27 阅读