search
HomeWeb Front-endVue.jsAn in-depth analysis of the life cycle functions in Vue3

An in-depth analysis of the life cycle functions in Vue3

Mar 13, 2023 pm 07:52 PM
vue3life cycle function

This article will lead you to learn the life cycle hook function of Vue3 combined API. Mastering the hook function gives us the opportunity to run our own logic at specific stages during the development process. I hope it will be helpful to everyone!

An in-depth analysis of the life cycle functions in Vue3

Life cycle hook function

Each Vue component instance is required when creating Go through a series of initialization steps, such as setting up data listening, compiling templates, mounting instances to the DOM, and updating the DOM when the data changes. Along the way, it also runs functions called lifecycle hooks, giving developers the opportunity to run their own code at specific stages.

In our Vue2, the this context of all life cycle hook functions will automatically point to the component instance that currently calls it.

Note: Avoid using arrow functions to define life cycle hooks, because if so you will not be able to get the component instance through this in the function. Below is a picture from the official website; an icon table of the instance life cycle. [Related recommendations: vuejs video tutorial, web front-end development]

An in-depth analysis of the life cycle functions in Vue3

beforeCreate
Will be called immediately after the instance initialization is completed, after the props are parsed, and before options such as data() and computed are processed. The setup() hook in the composite API is called before all optional API hooks, and beforeCreate() is no exception.

created
Called after the component instance has processed all state-related options. When this hook is called, the following has been set up: reactive data, computed properties, methods, and listeners. However, the mount phase has not yet started, so the $el property is still unavailable.

beforeMount
Called before the component is mounted. When this hook is called, the component has finished setting up its responsive state but has not yet created a DOM node. It is about to perform the DOM rendering process for the first time. This hook will not be called during server-side rendering.

mounted
Called after the component is mounted. A component is considered mounted when all synchronized subcomponents have been mounted. (Does not include asynchronous components or components within the <suspense></suspense> tree) Its own DOM tree has been created and inserted into the parent container. Note that only if the root container is in the document, the component DOM tree is guaranteed to be in the document. This hook is typically used to perform side effects that require access to the DOM tree rendered by the component, or in server-side rendering applications to ensure that DOM-related code is only called on the client side. This hook will not be called during server-side rendering.

beforeUpdate
Called just before the component is about to update its DOM tree due to a reactive state change. This hook can be used to access DOM state before Vue updates the DOM. It is also safe to change state in this hook. This hook will not be called during server-side rendering.

updated
Called after the component updates its DOM tree due to a reactive state change. The parent component's update hook will be called after the update hook of its child component. This hook will be called after any DOM update of the component, which may be caused by different state changes. If you need to access the updated DOM after a specific state change, use nextTick() instead. This hook will not be called during server-side rendering. Do not change the state of the component in the updated hook, this may cause an infinite update loop!

beforeUnmount(Vue3)
Called before a component instance is unmounted. When this hook is called, the component instance still retains full functionality. This hook will not be called during server-side rendering.

unmounted
Called after a component instance has been unmounted. A component is considered unloaded when all of its child components have been unloaded. All related reactive actions (rendering actions and computed properties and listeners created during setup()) have been stopped. Some side effects such as timers, DOM event listeners, or connections to the server can be manually cleaned up in this hook. This hook will not be called during server-side rendering.

activated
If the component instance is part of the <keepalive></keepalive> cache tree, called when the component is inserted into the DOM . This hook will not be called during server-side rendering.

deactivated
Called when the component is removed from the DOM if the component instance is part of the <keepalive></keepalive> cache tree. This hook will not be called during server-side rendering.


Combined API life cycle

We all know that life cycle functions are necessary in our development, so what should we do? How to use these hook functions in the combined API? In fact, it is very simple. You just need to remember that in the combined API, except for the two functions beforeCreate and created, other hook functions can be used in the setup by adding on. As for the two functions beforeCreate and created, they are not available in the combined API. Exists, because our execution in the setup entry function is before creation; our requests can be placed in the onMounted function, which is also the hook function we use more often; and all our hook functions in the combined API can Defined multiple times by .

Note that what we said earlier is not rigorous in that it can be used directly by adding on. We have two special ones, that is, our hook functions before and after destruction have changed, beforeDestroy=》onBoreUnmount, destroyed=》onUnmounted;

We mentioned above that the hook function in a combined API can be defined multiple times, so what is the meaning? In fact, many times we have this need. In our previous article, we mentioned that our Vue3 combined API has higher maintainability. Each logic is a separate code block. So if we Does the hook function that completes page initialization need to do two logical levels of processing? Then we need to write onMounted functions at different logical levels! Let’s first try to write the hook function in the combination API!

<template>
    <div>

    </div>
</template>

<script setup>
import { onBeforeMount, onMounted } from &#39;vue&#39;;
onMounted(() => {
    console.log(&#39;这是测试1&#39;)
})
onMounted(() => {
    console.log(&#39;这是测试2&#39;)
})

onBeforeMount(() => {
    console.log(&#39;这是测试3&#39;)
})
onBeforeMount(() => {
    console.log(&#39;这是测试4&#39;)
})
</script>

An in-depth analysis of the life cycle functions in Vue3

Here I will only show you the usage of the two hook functions onMounted and onBeforeMount. The same is true for the others. You can try it yourself later!


Write at the end

After reading this article, do you have a deeper understanding of Vue’s life cycle functions? Woolen cloth? Have you mastered the hook function usage of the combined API? And the hook function in our combined API can be defined multiple times, which can better reflect the maintainability and scalability of our combined API; of course, in this article, Brother Liang only led you to try two hook functions. , partners can try the rest of the hook functions on their own! Dear friends, let us let’s coding!

(Learning video sharing: vuejs introductory tutorial, Basic programming video)

The above is the detailed content of An in-depth analysis of the life cycle functions in Vue3. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
Vue.js vs. React: Scalability and MaintainabilityVue.js vs. React: Scalability and MaintainabilityMay 10, 2025 am 12:24 AM

Vue.js and React each have their own advantages in scalability and maintainability. 1) Vue.js is easy to use and is suitable for small projects. The Composition API improves the maintainability of large projects. 2) React is suitable for large and complex projects, with Hooks and virtual DOM improving performance and maintainability, but the learning curve is steeper.

The Future of Vue.js and React: Trends and PredictionsThe Future of Vue.js and React: Trends and PredictionsMay 09, 2025 am 12:12 AM

The future trends and forecasts of Vue.js and React are: 1) Vue.js will be widely used in enterprise-level applications and have made breakthroughs in server-side rendering and static site generation; 2) React will innovate in server components and data acquisition, and further optimize the concurrency model.

Netflix's Frontend: A Deep Dive into Its Technology StackNetflix's Frontend: A Deep Dive into Its Technology StackMay 08, 2025 am 12:11 AM

Netflix's front-end technology stack is mainly based on React and Redux. 1.React is used to build high-performance single-page applications, and improves code reusability and maintenance through component development. 2. Redux is used for state management to ensure that state changes are predictable and traceable. 3. The toolchain includes Webpack, Babel, Jest and Enzyme to ensure code quality and performance. 4. Performance optimization is achieved through code segmentation, lazy loading and server-side rendering to improve user experience.

Vue.js and the Frontend: Building Interactive User InterfacesVue.js and the Frontend: Building Interactive User InterfacesMay 06, 2025 am 12:02 AM

Vue.js is a progressive framework suitable for building highly interactive user interfaces. Its core functions include responsive systems, component development and routing management. 1) The responsive system realizes data monitoring through Object.defineProperty or Proxy, and automatically updates the interface. 2) Component development allows the interface to be split into reusable modules. 3) VueRouter supports single-page applications to improve user experience.

What are the disadvantages of VueJs?What are the disadvantages of VueJs?May 05, 2025 am 12:06 AM

The main disadvantages of Vue.js include: 1. The ecosystem is relatively new, and third-party libraries and tools are not as rich as other frameworks; 2. The learning curve becomes steep in complex functions; 3. Community support and resources are not as extensive as React and Angular; 4. Performance problems may be encountered in large applications; 5. Version upgrades and compatibility challenges are greater.

Netflix: Unveiling Its Frontend FrameworksNetflix: Unveiling Its Frontend FrameworksMay 04, 2025 am 12:16 AM

Netflix uses React as its front-end framework. 1.React's component development and virtual DOM mechanism improve performance and development efficiency. 2. Use Webpack and Babel to optimize code construction and deployment. 3. Use code segmentation, server-side rendering and caching strategies for performance optimization.

Frontend Development with Vue.js: Advantages and TechniquesFrontend Development with Vue.js: Advantages and TechniquesMay 03, 2025 am 12:02 AM

Reasons for Vue.js' popularity include simplicity and easy learning, flexibility and high performance. 1) Its progressive framework design is suitable for beginners to learn step by step. 2) Component-based development improves code maintainability and team collaboration efficiency. 3) Responsive systems and virtual DOM improve rendering performance.

Vue.js vs. React: Ease of Use and Learning CurveVue.js vs. React: Ease of Use and Learning CurveMay 02, 2025 am 12:13 AM

Vue.js is easier to use and has a smooth learning curve, which is suitable for beginners; React has a steeper learning curve, but has strong flexibility, which is suitable for experienced developers. 1.Vue.js is easy to get started with through simple data binding and progressive design. 2.React requires understanding of virtual DOM and JSX, but provides higher flexibility and performance advantages.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment