A complete guide to the life cycle of Vue 3


highlight: a11y-dark
theme: condensed-night-purple

Author: Michael Thiessen
Translator: Front Ash
Source: news

Like it and then look again , WeChat search **【Da Qian World, B station pays attention toFront-end Xiaozhi】** This person has no background in a big factory, but has a positive attitude towards upwards. This article GitHubhas been included on https://github.com/qq449245884/xiaozhi, 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, but it is not perfect enough. Welcome everyone to improve it together. I also hope that everyone can give a star to support it. Thank you.

github address: https://github.com/qq449245884/vue-okr-tree

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

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

image.png

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, we just need to call this method and write code for this lifecycle hook.

For example, if we want to access mounted()and updated()lifecycle hooks, we can write:

// 选项 API
<script>     
   export default {         
      mounted() {             
         console.log('mounted!')         
      },         
      updated() {             
         console.log('updated!')         
      }     
   }
</script> 

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.

// 组合 API
import { onMounted } from 'vue'

In addition to beforecateand created(they are replaced by the setupmethod itself), setupthere are 9 options for the API lifecycle hooks that we can access in the method:

  • onBeforeMount- to be called before mounting the beginning: the associated renderfunction is first called.

  • 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 the update, 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- to be keep-alivecalled when the cache activated components.

  • onDeactivated- to be keep-alivecalled when the cache disabled components.

  • 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 the source of the error. This hook can return falseto prevent the error continues to spread upwards.

Use case:

// 组合 API
<script>
import { onMounted } from 'vue'

export default {
   setup () {
     onMounted(() => {
       console.log('mounted in the composition api!')
     })
   }
}
</script>

Update the life cycle hook code of Vue2 to Vue3

This life cycle 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 life cycle hook

We now understand two important things:

  • Different lifecycle 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 the things that respond to data and events, it beforeCreatecannot access any response data and events of the component.

Take the following code block as an example:

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

valThe output value of is undefined, because the data has not been initialized, we cannot call the component method here.

If you want to view the complete list of available content, it is recommended to only 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 component when the component data and create an event, you can put the above beforeCreateused createdinstead.

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

The output is Value of val is: hellobecause we have initialized the data.

createdThe method used is very useful when dealing with read/write reaction data . 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 mountedof doing it in, because it happens 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 substitution beforecateand created. This means that any code placed in these methods is now only in setupmethods.

// 组合AP
import { ref } from 'vue'

export default {
   setup() {    
     const val = ref('hello') 
     console.log('Value of val is: ' + val.value)       
     return {         
       val
     }
   }
}

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.

// 选项 API
export default {
   beforeMount() {
     console.log(this.$el)
   }
 }

Use ref in the combined API:

// 组合 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)
    }
 }

Since it app.$elhas not been created yet, 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.$elto access our DOM, in the composite API, we need to use refsto access the DOM in the Vue lifecycle hook.

import { ref, onMounted } from 'vue'
 

 export default {
   setup() {    /* 组合 API */
 
     const root = ref(null)
 
     onMounted(() => {
       console.log(root.value)
     })
 

     return {
       root
     }
   },
   mounted() { /* 选项 API */
     console.log(this.$el)
   }
 } 

beforeUpdate() and onBeforeUpdate()

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

beforeUpdateIt 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, updatedthe 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> 

Option API method:

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

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
     }
   }
 }

These methods are useful, but for more scenarios, we need to use watchmethods to detect these data changes. watchIt'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() 和 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.

// 选项 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
      }
   }
} 
// 组合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);
     })
 
   }
 }

One method of actual operation is in 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() 和 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 () { /* 组合 API */

    onUnmounted(() => {
      console.log('unmounted')
    })

  },
  unmounted() { /* 选项 API */
    console.log('unmounted')
  }
}

activated() and onActivated()

It is keep-alivecalled when the cache activated components.

For example, if we use the keep-alivecomponent to manage different tab view, every time when switching between tabs, the current tab will run the activatedhook.

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 () { /* 组合 API */
    const tabName = ref('Tab1')

    return {
      tabName
    }
  }
}
</script>

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

<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>

deactivated() 和 onDeactivated()

It is keep-alivecalled when the cache disabled components.

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')
    })
  }
}

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

4216299740-605e8878b7355_fix732.gif

Vue3 debug hook

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

  1. onRenderTracked
  2. onRenderTriggered

Both of these events have one 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 eventas parameters. 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>
const app = Vue.createApp({
  data() {
    return {
      cart: 0
    }
  },
  renderTracked({ key, target, type }) {
    console.log({ key, target, type })
    /* 当组件第一次渲染时,这将被记录下来:
    {
      key: "cart",
      target: {
        cart: 0
      },
      type: "get"
    }
    */
  },
  methods: {
    addToCart() {
      this.cart += 1
    }
  }
})

app.mount('#app')

renderTracked

When the virtual re-DOM rendering triggered.Similarly is renderTrackedto receive debugger eventas 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>
const app = Vue.createApp({
  data() {
    return {
      cart: 0
    }
  },
  renderTriggered({ key, target, type }) {
    console.log({ key, target, type })
  },
  methods: {
    addToCart() {
      this.cart += 1
      /* 这将导致renderTriggered调用
        {
          key: "cart",
          target: {
            cart: 1
          },
          type: "set"
        }
      */
    }
  }
})

app.mount('#app')

to sum up

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 to know 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 think about 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.


The possible bugs after code deployment 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: https://learnvue.co/2020/12/how-to-use-lifecycle-hooks-in-vue3/

communicate with

The article is continuously updated every week, and you can search for "Da Qian World" on WeChat to read and update as soon as possible (one or two earlier than the blog). This article has been included on GitHub https://github.com/qq449245884/xiaozhi A lot of my documents are 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 to see the benefits. You know.

Guess you like

Origin blog.csdn.net/qq449245884/article/details/115341203