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生命周期链接
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 |