A complete guide to the life cycle of Vue 3

A complete guide to the life cycle of Vue 3

Author: Michael Thiessen Translator: Front-end Wisdom Source: news

Like it and then look again , WeChat search ** Da Qian World , B station pays attention to Front-end Xiaozhi ** This person has no background in a big factory, but has a positive attitude. This article

GitHub
github.com/qq449245884 ... has been included, the article has been classified, and a lot of my documents and tutorial materials have been sorted out.

Recently, a Vue component has been open sourced, which is not perfect enough. Welcome everyone to improve it together. I also hope that you can give a star to support it. Thank you.

github address: github.com/qq449245884...

The lifecycle hooks in Vue2 and Vue3 work very similarly. We can still access the same hooks and hope that they can be used in the same scenarios.

If the project uses the option API , you do not have to change any code, because Vue3 compatible with previous versions.

Of course, we Vue3 it is to use a combination of API , a combination of API way to access these hooks are slightly different combinations API is particularly useful in larger Vue project.

The main content of this article:

  1. What are the Vue lifecycle hooks
  2. Use Vue lifecycle hooks in the options API
  3. Use Vue 3 lifecycle hooks in the composite API
  4. Update the life cycle hook code of Vue2 to Vue3
  5. Take a look at every lifecycle hook in Vue 2 and Vue 3
  6. create
  7. Mount
  8. Update
  9. Uninstall
  10. activation
  11. New debugging hooks in Vue 3

What are the Vue lifecycle hooks

1. let's take a look at the diagram of the Vue 3 lifecycle hooks in the options API and combination API. This can deepen our understanding before going into the details.

Essentially, each major Vue lifecycle event is divided into two hooks, which are called before and after the event. There are 4 main events (8 main hooks) in the Vue application.

  • Create execute when the component is created
  • Mount execute when the DOM is mounted
  • Update execute when the response data is modified
  • Destroy run immediately before the element is destroyed

Use Vue lifecycle hooks in the options API

Using the options API, lifecycle hooks are options that are exposed on the Vue instance. We don't need to import anything, just call this method and write code for this lifecycle hook.

For example, suppose we want to visit

mounted()
with
updated()
The life cycle hook can be written like this:

//Option API <script> export default { mounted() { console.log('mounted!') }, updated() { console.log('updated!') } } </script> Copy code

Use Vue 3 lifecycle hooks in the composite API

In the composite API, we need to import the lifecycle hook into the project before it can be used, which helps to keep the project lightweight.

//Combination API import {onMounted} from'vue' Copy code

apart from

beforecate
with
created
(They are
setup
Method itself), we can
setup
There are 9 options for the API lifecycle hook accessed in the method:

  • onBeforeMount
    Called before the start of the mount: relevant
    render
    The function is called for the first time.

  • onMounted
    -Called when the component is mounted

  • onBeforeUpdate
    Called when the data is updated, before the virtual DOM is patched. This is suitable for accessing the existing DOM before updating, such as manually removing the added event listener.

  • onUpdated
    The virtual DOM is re-rendered and patched due to data changes, after which the hook will be called.

  • onBeforeUnmount-called before unmounting the component instance. At this stage, the instance is still completely normal.

  • onUnmounted
    Called after the component instance is uninstalled. When this hook is called, all instructions of the component instance are unbound, all event listeners are removed, and all child component instances are unloaded.

  • onActivated
    Be
    keep-alive
    Called when the cached component is activated.

  • onDeactivated
    Be
    keep-alive
    Called when the cached component is deactivated.

  • onErrorCaptured
    -Called when an error from descendant components is caught. This hook will receive three parameters: the error object, the component instance where the error occurred, and a string containing information about the source of the error. This hook can return
    false
    To prevent the error from continuing to propagate upward.

Use case:

//Combination API <script> import {onMounted} from'vue' export default { setup () { onMounted(() => { console.log('mounted in the composition api!') }) } } </script> Copy code

Update the life cycle hook code of Vue2 to Vue3

This lifecycle mapping from Vue2 to Vue3 is obtained directly from the Vue 3 Composition API documentation:

  • beforeCreate
    -> Use
    setup()

  • created
    -> Use
    setup()

  • beforeMount
    ->
    onBeforeMount

  • mounted
    ->
    onMounted

  • beforeUpdate
    ->
    onBeforeUpdate

  • updated
    ->
    onUpdated

  • beforeDestroy
    ->
    onBeforeUnmount

  • destroyed
    ->
    onUnmounted

  • errorCaptured
    ->
    onErrorCaptured

In-depth understanding of each lifecycle hook

We now understand two important things:

  • Different life cycle hooks we can use
  • How to use them in option API and combination API

Let's dive into each lifecycle hook to see how they are used. We can write specific code in each hook to test the differences between the Options API and the Composition API.

beforeCreate() Options API

Since the created hook is used to initialize all things that respond to data and events,

beforeCreate
Cannot access any response data and events of the component.

Take the following code block as an example:

//Option API export default { data() { return { val:'hello' } }, beforeCreate() { console.log('Value of val is: '+ this.val) } } Copy code

val
The output value is
undefined
, Because the data has not yet been initialized, we cannot call component methods here either.

If you want to see the complete list of available content, it is recommended to just run

console.log(this)
To view the initialized content. This approach is also useful in other hooks when using the options API.

created() Options API

If we want to access the data and events of the component when it is created, we can put the above

beforeCreate
use
created
instead.

//Option API export default { data() { return { val:'hello' } }, created() { console.log('Value of val is: '+ this.val) } } Copy code

Its output is

Value of val is: hello
, Because we have initialized the data.

When processing read/write response data, use

created
The method is very useful. For example, to make an API call and then store the value, you can do this here.

It s better to do this here instead of

mounted
This operation is performed in Vue, because it occurs during the synchronization initialization process of Vue, and we need to perform all data read/write operations.

What about the creation hook of the composite API?

For Vue3 lifecycle hooks that use composite APIs, use

setup()
Method replacement
beforecate
with
created
. This means that any code placed in these methods is now only in
setup
Method.

//Combine AP import {ref} from'vue' export default { setup() { const val = ref('hello') console.log('Value of val is: '+ val.value) return { val } } } Copy code

beforeMount() and onBeforeMount()

Called before the component DOM is actually rendered and installed. In this step, the root element does not yet exist. In the options API, you can use this.$els to access. In the composite API, in order to do this, it must be used on the root element

ref
.

//Option API export default { beforeMount() { console.log(this.$el) } } Copy code

Use ref in the combined API:

//Combination API <template> <div ref='root'> Hello World </div> </template> import {ref, onBeforeMount} from'vue' export default { setup() { const root = ref(null) onBeforeMount(() => { console.log(root.value) }) return { root } }, beforeMount() { console.log(this.$el) } } Copy code

because

app.$el
Has not been created yet, so the output will be
undefined
.

mounted() and onMounted()

Called after the first rendering of the component, the element is now available, allowing direct DOM access

Similarly, in the options API, we can use

this.$el
To access our DOM, in the composite API, we need to use
refs
To access the DOM in the Vue lifecycle hook.

import {ref, onMounted} from'vue' export default { setup() {/* Combination API */ const root = ref(null) onMounted(() => { console.log(root.value) }) return { root } }, mounted() {/* Option API */ console.log(this.$el) } } Copy code

beforeUpdate() and onBeforeUpdate()

Called when the data is updated, before the virtual DOM is patched. This is suitable for accessing the existing DOM before updating, such as manually removing the added event listener.

beforeUpdate
It is useful for tracking the number of edits to a component, or even the creation of an "undo" function.

updated() and onUpdated()

After the DOM is updated,

updated
The method will be called.

<template> <div> <p>{{val}} | edited {{ count }} times</p> <button @click='val = Math.random(0, 100)'>Click to Change</button> </div> </template> Copy code

Option API method:

export default { data() { return { val: 0 } }, beforeUpdate() { console.log("beforeUpdate() val: "+ this.val) }, updated() { console.log("updated() val: "+ this.val } } Copy code

Ways to combine API:

import {ref, onBeforeUpdate, onUpdated} from'vue' export default { setup () { const count = ref(0) const val = ref(0) onBeforeUpdate(() => { count.value++; console.log("beforeUpdate"); }) onUpdated(() => { console.log("updated() val: "+ val.value) }) return { count, val } } } Copy code

These methods are very useful, but for more scenarios, we need to use

watch
Method to detect these data changes.
watch
It's easy to use because it gives the old and new values of the changed data.

Another option is to use calculated attributes to change the state based on the element.

beforeUnmount() and onBeforeUnmounted()

Called before uninstalling the component instance. At this stage, the instance is still completely normal.

In the options API, an example of deleting an event listener is shown below.

//Option API export default { mounted() { console.log('mount') window.addEventListener('resize', this.someMethod); }, beforeUnmount() { console.log('unmount') window.removeEventListener('resize', this.someMethod); }, methods: { someMethod() { //do smth } } } Copy code
//Combination API import {onMounted, onBeforeUnmount} from'vue' export default { setup () { const someMethod = () => { //do smth } onMounted(() => { console.log('mount') window.addEventListener('resize', someMethod); }) onBeforeUnmount(() => { console.log('unmount') window.removeEventListener('resize', someMethod); }) } } Copy code

One way to actually operate is to use Vite, vue-cli or any development environment that supports hot reloading. When the code is updated, some components will be uninstalled and installed by themselves.

unmounted() and onUnmounted()

Called after the component instance is uninstalled. When this hook is called, all instructions of the component instance are unbound, all event listeners are removed, and all child component instances are unloaded.

import {onUnmounted} from'vue' export default { setup () {/* Combination API */ onUnmounted(() => { console.log('unmounted') }) }, unmounted() {/* Option API */ console.log('unmounted') } } Copy code

activated() and onActivated()

Be

keep-alive
Called when the cached component is activated.

For example, if we use

keep-alive
Component to manage different tab views, each time you switch between tabs, the current tab will run this
activated
hook.

Suppose we use keep-alive wrapper for the following dynamic components.

<template> <div> <span @click='tabName = "Tab1"'>Tab 1 </span> <span @click='tabName = "Tab2"'>Tab 2</span> <keep-alive> <component :is='tabName' class='tab-area'/> </keep-alive> </div> </template> <script> import Tab1 from'./Tab1.vue' import Tab2 from'./Tab2.vue' import {ref} from'vue' export default { components: { Tab1, Tab2 }, setup () {/* Combination API */ const tabName = ref('Tab1') return { tabName } } } </script> Copy code

Inside the Tab1.vue component, we can access like this

activated
hook.

<template> <div> <h2>Tab 1</h2> <input type='text' placeholder='this content will persist!'/> </div> </template> <script> import {onActivated} from'vue' export default { setup() { onActivated(() => { console.log('Tab 1 Activated') }) } } </script> Copy code

deactivated() and onDeactivated()

Be

keep-alive
Called when the cached component is deactivated.

This hook is useful in some use cases, such as saving user data and triggering animations when a particular view loses focus.

import {onActivated, onDeactivated} from'vue' export default { setup() { onActivated(() => { console.log('Tab 1 Activated') }) onDeactivated(() => { console.log('Tab 1 Deactivated') }) } } Copy code

Now, when we switch between tabs, the state of each dynamic component will be cached and saved.

Vue3 debug hook

Vue3 provides us with two hooks that can be used for debugging purposes.

  1. onRenderTracked
  2. onRenderTriggered

Both of these events carry a

debugger event
, This event tells you which operation is tracking the component and the target object and key of the operation.

onRenderTracked

Called when tracking virtual DOM re-rendering. Hook receiving

debugger event
As a parameter. This event tells you which operation is tracking the component and the target object and key of the operation.

<div id="app"> <button v-on:click="addToCart">Add to cart</button> <p>Cart({{ cart }})</p> </div> Copy code
const app = Vue.createApp({ data() { return { cart: 0 } }, renderTracked({ key, target, type }) { console.log({ key, target, type }) /* This will be recorded when the component is rendered for the first time: { key: "cart", target: { cart: 0 }, type: "get" } */ }, methods: { addToCart() { this.cart += 1 } } }) app.mount('#app') Copy code

renderTracked

When the virtual DOM is re-rendered as triggered.Similarly is

,receive
debugger event
As a parameter. This event tells you what operation triggered the re-rendering, as well as the target object and key of the operation.

usage:

<div id="app"> <button v-on:click="addToCart">Add to cart</button> <p>Cart({{ cart }})</p> </div> Copy code
const app = Vue.createApp({ data() { return { cart: 0 } }, renderTriggered({ key, target, type }) { console.log({ key, target, type }) }, methods: { addToCart() { this.cart += 1 /* This will cause renderTriggered to be called { key: "cart", target: { cart: 1 }, type: "set" } */ } } }) app.mount('#app') Copy code

summary

Whether you choose to use the option API or the composite API, it is important not only to know which lifecycle hook to use, but also why you want to use it.

For many problems, multiple lifecycle hooks can be used. But it's best to know which is best for your use case. In any case, you should consider it carefully and have a good reason to choose a specific lifecycle hook.

I hope this helps you understand more about lifecycle hooks and how to implement them in your projects.

~ End, I m Shuwanzhi, I m going to clean the dishes, the bones are white.


After the code is deployed, the possible bugs cannot be known in real time. In order to solve these bugs afterwards, a lot of time was spent on log debugging. By the way, I would like to recommend a useful BUG monitoring tool Fundebug .

Original: learnvue.co/2020/12/how...

communicate with

The article is continuously updated every week, and you can search for "Da Qian World" on WeChat to read and update it as soon as possible (one or two earlier than the blog), this article GitHub github.com/qq449245884...has been included, and a lot of my documents have been sorted out. Welcome to Star and perfect. You can refer to the test site for review during interviews. In addition, follow the official account and reply to the benefits in the background . You can see the benefits, you know.