vue.js 2和vue.js 3的生命周期与对应的钩子函数区别

options api

以下表格对应options api

|-----|-------------------------------------------------|---------------------------------------------------------------------------------|
| | vue.js 2 | vue.js 3 |
| 创建时 | beforeCreate created | setup() 代替了beforeCreate和created beforeCreate created |
| 挂载时 | beforeMount mounted 网咯请求放到这里 | beforeMount mounted 网咯请求放到这里 |
| 更新时 | beforeUpdate updated | beforeUpdate updated |
| 卸载时 | beforeDestroy 卸载之前,把消耗性能的处理都处理掉,例如定时器 destroyed | beforeUnmount(beforeDestroy的替代) 卸载之前,把消耗性能的处理都处理掉,例如定时器 unmounted(destroyed的替代) |

vue.js 2生命周期链接

https://v2.cn.vuejs.org/v2/guide/instance.html#%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E5%9B%BE%E7%A4%BA

vue.js 3生命周期链接

https://cn.vuejs.org/guide/essentials/lifecycle

composition api

以下是 vue.js 3中新增的

onMounted
组件挂载完成时

onUpdated
组件更新完成时

onUnmounted
组件卸载完成时

必须在 setup()函数中同步调用,不能在 setup 外部使用,也不能在异步回调中调用。为了简化使用,直接在script标签中指定setup即可,如下代码

复制代码
<script setup>
import { ref, onMounted } from 'vue'
const count = ref(0)

function increment() {
  count.value++
}

onMounted(() => {
  console.log('mounted')
})
</script>

vue.js 3中options api和composition api的区别

|-----|-------------------------------------------------|-----------------------------------------------------|
| | options api | composition api |
| 创建时 | beforeCreate created | setup() 代替了beforeCreate和created |
| 挂载时 | beforeMount mounted 网咯请求放到这里 | onBeforeMount onMounted 网咯请求放到这里 |
| 更新时 | beforeUpdate updated | onBeforeUpdate onUpdated |
| 卸载时 | beforeUnmount 卸载之前,把消耗性能的处理都处理掉,例如定时器 unmounted | onBeforeUnmount 卸载之前,把消耗性能的处理都处理掉,例如定时器 onUnmounted |

相关推荐
于慨1 天前
Lambda 表达式、方法引用(Method Reference)语法
java·前端·servlet
石小石Orz1 天前
油猴脚本实现生产环境加载本地qiankun子应用
前端·架构
从前慢丶1 天前
前端交互规范(Web 端)
前端
像我这样帅的人丶你还1 天前
别再让JS耽误你进步了。
css·vue.js
@yanyu6661 天前
07-引入element布局及spring boot完善后端
javascript·vue.js·spring boot
CHU7290351 天前
便捷约玩,沉浸推理:线上剧本杀APP功能版块设计详解
前端·小程序
GISer_Jing1 天前
Page-agent MCP结构
前端·人工智能
王霸天1 天前
💥别再抄网上的Scale缩放代码了!50行源码教你写一个永不翻车的大屏适配
前端·vue.js·数据可视化
小领航1 天前
用 Three.js + Vue 3 打造炫酷的 3D 行政地图可视化组件
前端·github
@大迁世界1 天前
2026年React大洗牌:React Hooks 将迎来重大升级
前端·javascript·react.js·前端框架·ecmascript