Vue 3中,Options API (选项型)和 Composition API (组合型)生命周期钩子的图表:
1、使用 Options API,生命周期钩子作为选项暴露在Vue 实例上。 不需要引入任何东西, 例如:
<script>
export default {
mounted() {
console.log('mounted!')
},
updated() {
console.log('updated!')
}
}
</script>
2、使用 Composition API, 需要从vue中引入,例如:
<script>
import { onMounted } from 'vue'
export default {
setup () {
onMounted(() => {
console.log('mounted in the composition api!')
});
onUpdated(() => {
console.log('updated in the composition api!')
});
}
}
</script>
beforeCreate
and created
,are replaced by the setup
method itself.
onBeforeMount | called before mounting begins |
onMounted | called when component is mounted |
onBeforeUpdate | called when reactive data changes and before re-render |
onUpdated | called after re-render |
onBeforeUnmount | called before the Vue instance is destroyed |
onUnmounted | called after the instance is destroyed |
onActivated | called when a kept-alive component is activated |
onDeactivated | called when a kept-alive component is deactivated |
onErrorCaptured | called when an error is captured from a child component |
3、
vue2 | vue3 |
beforeCreate | setup |
created | setup |
beforeMount | beforeMount |
mounted | mounted |
beforeUpdate | beforeUpdate |
updated | updated |
beforeDestroy | beforeUnmount |
destroyed | unmounted |
errorCaptured | errorCaptured |
更多详情请参考下列文章:
参考文章:A Complete Guide to Vue Lifecycle Hooks - with Vue 3 Updates - LearnVue