An in-depth analysis of the life cycle functions in Vue3
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!
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]
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 'vue'; onMounted(() => { console.log('这是测试1') }) onMounted(() => { console.log('这是测试2') }) onBeforeMount(() => { console.log('这是测试3') }) onBeforeMount(() => { console.log('这是测试4') }) </script>
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

tinymce is a fully functional rich text editor plug-in, but introducing tinymce into vue is not as smooth as other Vue rich text plug-ins. tinymce itself is not suitable for Vue, and @tinymce/tinymce-vue needs to be introduced, and It is a foreign rich text plug-in and has not passed the Chinese version. You need to download the translation package from its official website (you may need to bypass the firewall). 1. Install related dependencies npminstalltinymce-Snpminstall@tinymce/tinymce-vue-S2. Download the Chinese package 3. Introduce the skin and Chinese package. Create a new tinymce folder in the project public folder and download the

To achieve partial refresh of the page, we only need to implement the re-rendering of the local component (dom). In Vue, the easiest way to achieve this effect is to use the v-if directive. In Vue2, in addition to using the v-if instruction to re-render the local dom, we can also create a new blank component. When we need to refresh the local page, jump to this blank component page, and then jump back in the beforeRouteEnter guard in the blank component. original page. As shown in the figure below, how to click the refresh button in Vue3.X to reload the DOM within the red box and display the corresponding loading status. Since the guard in the component in the scriptsetup syntax in Vue3.X only has o

vue3+vite:src uses require to dynamically import images and error reports and solutions. vue3+vite dynamically imports multiple images. If vue3 is using typescript development, require will introduce image errors. requireisnotdefined cannot be used like vue2 such as imgUrl:require(' .../assets/test.png') is imported because typescript does not support require, so import is used. Here is how to solve it: use awaitimport

Vue implements the blog front-end and needs to implement markdown parsing. If there is code, it needs to implement code highlighting. There are many markdown parsing libraries for Vue, such as markdown-it, vue-markdown-loader, marked, vue-markdown, etc. These libraries are all very similar. Marked is used here, and highlight.js is used as the code highlighting library. The specific implementation steps are as follows: 1. Install dependent libraries. Open the command window under the vue project and enter the following command npminstallmarked-save//marked to convert markdown into htmlnpmins

Preface Whether it is vue or react, when we encounter multiple repeated codes, we will think about how to reuse these codes instead of filling a file with a bunch of redundant codes. In fact, both vue and react can achieve reuse by extracting components, but if you encounter some small code fragments and you don’t want to extract another file, in comparison, react can be used in the same Declare the corresponding widget in the file, or implement it through renderfunction, such as: constDemo:FC=({msg})=>{returndemomsgis{msg}}constApp:FC=()=>{return(

vue3+ts+axios+pinia realizes senseless refresh 1. First download aiXos and pinianpmipinia in the project--savenpminstallaxios--save2. Encapsulate axios request-----Download js-cookienpmiJS-cookie-s//Introduce aixosimporttype{AxiosRequestConfig ,AxiosResponse}from"axios";importaxiosfrom'axios';import{ElMess

The final effect is to install the VueCropper component yarnaddvue-cropper@next. The above installation value is for Vue3. If it is Vue2 or you want to use other methods to reference, please visit its official npm address: official tutorial. It is also very simple to reference and use it in a component. You only need to introduce the corresponding component and its style file. I do not reference it globally here, but only introduce import{userInfoByRequest}from'../js/api' in my component file. import{VueCropper}from'vue-cropper&

Using Vue to build custom elements WebComponents is a collective name for a set of web native APIs that allow developers to create reusable custom elements (customelements). The main benefit of custom elements is that they can be used with any framework, even without one. They are ideal when you are targeting end users who may be using a different front-end technology stack, or when you want to decouple the final application from the implementation details of the components it uses. Vue and WebComponents are complementary technologies, and Vue provides excellent support for using and creating custom elements. You can integrate custom elements into existing Vue applications, or use Vue to build
