Detailed vue3 life cycle

Detailed vue3 life cycle

In Vue3, the number and names of lifecycle hook functions have changed. There are two new lifecycle hook functions in Vue3: beforeUnmount and unmounted, while merging the previous beforeCreate and created into one setup hook function.

The following is the life cycle hook function of Vue3:

setup: At the beginning of the creation of the component instance, the component instance has been created at this time, but the properties such as data and props have not been initialized. Some data initialization operations can be performed in this hook function.

beforeMount: The component is about to be mounted into the DOM tree, and the template of the component has been compiled at this time.

onMounted: The component is successfully mounted to the DOM tree, and the DOM can be manipulated at this time.

onBeforeUpdate: The component's data is about to be updated, called before re-rendering.

onUpdated: The data of the component has been updated and the DOM has been re-rendered.

onUnmounted: The component is about to be unmounted, and some cleaning work can be done at this time, such as canceling the timer, unbinding events, etc.

onErrorCaptured: Called when an error from a descendant component is captured.

beforeUnmount: Called before the component is unmounted, you can do some final cleanup here.

unmounted: The component has been destroyed, and all the content of the component has been removed from the DOM tree at this time.

It should be noted that in Vue3, the beforeCreate and created hook functions are merged into setup, and the this keyword cannot be used in the setup function, but a new responsive API is adopted.

import {
    
     onMounted, onUnmounted } from 'vue';

export default {
    
    
  setup() {
    
    
    const message = 'Hello, Vue3!';

    onMounted(() => {
    
    
      console.log('mounted');
    });

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

    return {
    
    
      message
    };
  }
};

By using Vue3's lifecycle hook function, you can better manage the lifecycle of component instances and avoid problems such as memory leaks.

Guess you like

Origin blog.csdn.net/weixin_45357661/article/details/130457119