Vue.js 3.0 Tutorial

Vue.js 3.0 Component Advanced

Vue.js 3.0 Transitions & Animations

Vue.js 3.0 Reusable & Combinable

Vue.js 3.0 Advanced

Vue.js 3.0 Tools

Vue.js 3.0 Scale

Vue.js 3.0 Accessibility

Vue.js 3.0 Migrating from Vue2

Vue.js 3.0 Contribute Documentation

Vue.js 3.0 API References

Vue.js 3.0 Style Guide

Vue 3.0 compose API lifecycle hooks

In Vue 3, the new Composition API was introduced to tackle limitations of the Options API in complex applications. The Composition API is not meant to replace the Options API, but rather provides an additional set of tools for more granular and logical code organization.

One important aspect of the Composition API is the equivalent of lifecycle hooks. If you've worked with Vue's Options API, you're probably familiar with hooks like created, mounted, updated, etc. These hooks are still available, but in the Composition API, you need to import them as functions from vue.

Here's how to use the lifecycle hooks in Vue 3.0 Composition API:

First, you need to import the lifecycle hooks and setup from Vue:

import { onMounted, onUpdated, onUnmounted } from 'vue';

Then, inside your component's setup function, you can use these lifecycle hooks:

export default {
  setup() {
    // onMounted
    onMounted(() => {
      console.log('Component has been mounted');
    });

    // onUpdated
    onUpdated(() => {
      console.log('Component has been updated');
    });

    // onUnmounted
    onUnmounted(() => {
      console.log('Component has been unmounted');
    });
  },
};

Just like in the Options API, onMounted is called when the component is mounted, onUpdated is called when a reactive dependency changes, and onUnmounted is called when the component is unmounted.

Note that unlike in the Options API, lifecycle hooks are called inside the setup function in the order they are placed. This allows you to logically group lifecycle logic with its corresponding reactive data, leading to better code organization.

Another important point to note is that this is not available inside the setup method, as the setup method is called before the creation of the component instance. Hence all the props, data, methods should be returned from the setup method.

Here is an example of using lifecycle hooks with reactive data:

import { ref, onMounted } from 'vue';

export default {
  setup() {
    const count = ref(0);

    onMounted(() => {
      setInterval(() => {
        count.value++;
      }, 1000);
    });

    return {
      count
    }
  }
}

In this example, count is a reactive reference that is incremented every second after the component is mounted. You can display the count in your template with {{ count }}.

  1. Using Lifecycle Hooks with Composition API in Vue 3.0:

    • The Composition API introduces a set of lifecycle hooks that allow you to perform actions at different stages of a component's lifecycle.

    • Example code:

      <!-- LifecycleHooksExample.vue -->
      <template>
        <div>{{ message }}</div>
      </template>
      
      <script>
      import { ref, onMounted, onUpdated, onUnmounted } from 'vue';
      
      export default {
        setup() {
          const message = ref('Hello from Composition API!');
      
          onMounted(() => {
            console.log('Component mounted');
          });
      
          onUpdated(() => {
            console.log('Component updated');
          });
      
          onUnmounted(() => {
            console.log('Component unmounted');
          });
      
          return { message };
        },
      };
      </script>
      
  2. Vue 3.0 beforeCreate and created Hooks in Composition API:

    • beforeCreate is called before the instance is initialized, and created is called after the instance is created but before mounting.

    • Example code:

      <!-- BeforeCreateCreated.vue -->
      <script>
      import { ref, onBeforeCreate, onCreated } from 'vue';
      
      export default {
        setup() {
          const message = ref('Hello');
      
          onBeforeCreate(() => {
            console.log('Before Create Hook');
          });
      
          onCreated(() => {
            console.log('Created Hook');
          });
      
          return { message };
        },
      };
      </script>
      
  3. Vue 3.0 beforeMount and mounted Hooks in Composition API:

    • beforeMount is called before the component is mounted, and mounted is called after the component is mounted.

    • Example code:

      <!-- BeforeMountMounted.vue -->
      <script>
      import { ref, onBeforeMount, onMounted } from 'vue';
      
      export default {
        setup() {
          const message = ref('Hello');
      
          onBeforeMount(() => {
            console.log('Before Mount Hook');
          });
      
          onMounted(() => {
            console.log('Mounted Hook');
          });
      
          return { message };
        },
      };
      </script>
      
  4. Lifecycle Hooks Order in Vue 3.0 Composition API:

    • The order of lifecycle hooks execution in the Composition API follows a specific sequence.

    • Example code:

      <!-- LifecycleOrder.vue -->
      <script>
      import { ref, onBeforeCreate, onCreated, onBeforeMount, onMounted } from 'vue';
      
      export default {
        setup() {
          const message = ref('Hello');
      
          onBeforeCreate(() => {
            console.log('Before Create Hook');
          });
      
          onCreated(() => {
            console.log('Created Hook');
          });
      
          onBeforeMount(() => {
            console.log('Before Mount Hook');
          });
      
          onMounted(() => {
            console.log('Mounted Hook');
          });
      
          return { message };
        },
      };
      </script>
      
  5. Vue 3.0 beforeUpdate and updated Hooks in Composition API:

    • beforeUpdate is called before a component's state or props change, and updated is called after the component is re-rendered.

    • Example code:

      <!-- BeforeUpdateUpdated.vue -->
      <script>
      import { ref, onBeforeUpdate, onUpdated } from 'vue';
      
      export default {
        setup() {
          const message = ref('Hello');
      
          onBeforeUpdate(() => {
            console.log('Before Update Hook');
          });
      
          onUpdated(() => {
            console.log('Updated Hook');
          });
      
          return { message };
        },
      };
      </script>
      
  6. Vue 3.0 beforeUnmount and unmounted Hooks in Composition API:

    • beforeUnmount is called before a component is unmounted, and unmounted is called after the component is unmounted.

    • Example code:

      <!-- BeforeUnmountUnmounted.vue -->
      <script>
      import { ref, onBeforeUnmount, onUnmounted } from 'vue';
      
      export default {
        setup() {
          const message = ref('Hello');
      
          onBeforeUnmount(() => {
            console.log('Before Unmount Hook');
          });
      
          onUnmounted(() => {
            console.log('Unmounted Hook');
          });
      
          return { message };
        },
      };
      </script>
      
  7. Handling Error Hooks in Vue 3.0 Composition API:

    • Error hooks like onErrorCaptured allow you to handle errors in the Composition API.

    • Example code:

      <!-- ErrorHooks.vue -->
      <script>
      import { ref, onErrorCaptured } from 'vue';
      
      export default {
        setup() {
          const message = ref('Hello');
      
          onErrorCaptured((error, component, info) => {
            console.error('Error captured:', error);
            console.log('Component:', component);
            console.log('Info:', info);
          });
      
          return { message };
        },
      };
      </script>
      
  8. Vue 3.0 onRender and onMounted Hooks in Composition API:

    • onRender is an experimental hook that allows you to perform actions during the rendering phase.

    • Example code:

      <!-- OnRenderMounted.vue -->
      <script>
      import { ref, onRender, onMounted } from 'vue';
      
      export default {
        setup() {
          const message = ref('Hello');
      
          onRender(() => {
            console.log('Render phase');
          });
      
          onMounted(() => {
            console.log('Mounted Hook');
          });
      
          return { message };
        },
      };
      </script>
      
  9. Vue 3.0 onUpdated and onUnmounted Hooks in Composition API:

    • onUpdated is called after a component is re-rendered, and onUnmounted is called after a component is unmounted.

    • Example code:

      <!-- OnUpdatedOnUnmounted.vue -->
      <script>
      import { ref, onUpdated, onUnmounted } from 'vue';
      
      export default {
        setup() {
          const message = ref('Hello');
      
          onUpdated(() => {
            console.log('Updated Hook');
          });
      
          onUnmounted(() => {
            console.log('Unmounted Hook');
          });
      
          return { message };
        },
      };
      </script>
      
  10. Lifecycle Hooks and Reactivity in Vue 3.0 Composition API:

    • Lifecycle hooks in the Composition API seamlessly integrate with reactivity, allowing you to access and modify reactive data.

    • Example code:

      <!-- LifecycleReactivity.vue -->
      <script>
      import { ref, onMounted, onUpdated, onUnmounted } from 'vue';
      
      export default {
        setup() {
          const message = ref('Hello');
      
          onMounted(() => {
            setTimeout(() => {
              message.value = 'Updated message after mount';
            }, 2000);
          });
      
          onUpdated(() => {
            console.log('Message updated:', message.value);
          });
      
          onUnmounted(() => {
            console.log('Component unmounted');
          });
      
          return { message };
        },
      };
      </script>
      
  11. Vue 3.0 Lifecycle Hooks for Component Teardown in Composition API:

    • Lifecycle hooks like onBeforeUnmount and onUnmounted are used for cleanup and teardown tasks before and after component unmounting.

    • Example code:

      <!-- ComponentTeardown.vue -->
      <script>
      import { ref, onBeforeUnmount, onUnmounted } from 'vue';
      
      export default {
        setup() {
          const cleanupTasks = ref([]);
      
          const addCleanupTask = (task) => {
            cleanupTasks.value.push(task);
          };
      
          onBeforeUnmount(() => {
            console.log('Before Unmount Hook');
            cleanupTasks.value.forEach((task) => task());
          });
      
          onUnmounted(() => {
            console.log('Unmounted Hook');
          });
      
          return { addCleanupTask };
        },
      };
      </script>
      
  12. Using Lifecycle Hooks for Side Effects in Vue 3.0 Composition API:

    • Lifecycle hooks are often used for side effects such as data fetching, subscriptions, or event listeners.

    • Example code:

      <!-- SideEffects.vue -->
      <script>
      import { ref, onMounted, onUnmounted } from 'vue';
      
      export default {
        setup() {
          const fetchData = () => {
            // Perform data fetching logic
          };
      
          onMounted(() => {
            console.log('Mounted Hook');
            fetchData();
          });
      
          onUnmounted(() => {
            console.log('Unmounted Hook');
            // Clean up subscriptions or event listeners
          });
      
          return {};
        },
      };
      </script>