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 |

相关推荐
你们瞎搞19 小时前
Cesium加载20GB航测影像.tif
前端·cesium·gdal·地图切片
南山安19 小时前
Tailwind CSS:顺风CSS
javascript·css·react.js
milanleon20 小时前
使用Spring Security进行登录认证
java·前端·spring
excel20 小时前
🚀 从零开始:如何从 GPTsAPI.net 申请 API Key 并打造自己的 AI 服务
前端
期待のcode20 小时前
@RequestBody的伪表单提交场景
java·前端·vue.js·后端
栀秋66621 小时前
防抖 vs 节流:从百度搜索到京东电商,看前端性能优化的“节奏哲学”
前端·javascript
一颗烂土豆21 小时前
vfit.js v2.0.0 发布:精简、语义化与核心重构 🎉
前端·vue.js·响应式设计
有意义21 小时前
深入防抖与节流:从闭包原理到性能优化实战
前端·javascript·面试
可观测性用观测云21 小时前
网站/接口可用性拨测最佳实践
前端
2503_9284115621 小时前
12.26 小程序问题和解决
前端·javascript·微信小程序·小程序