In Vue.js 3, the Composition API offers a new approach to organizing and reusing logic, with access to component lifecycle hooks. In the Composition API, we access these lifecycle hooks using specific functions. These functions correspond to those in the traditional Options API but are used differently. Below are the methods for accessing and using these lifecycle hooks in the Composition API.
Basic Lifecycle Hooks
First, import the necessary lifecycle hook functions. Vue 3 provides several functions such as onMounted, onUpdated, and onUnmounted, which can be directly imported from the vue package.
javascriptimport { onMounted, onUnmounted, onUpdated } from 'vue';
Using onMounted
The onMounted hook runs after the component is mounted to the DOM. This is an ideal time to initialize or start asynchronous operations.
javascriptimport { onMounted } from 'vue'; export default { setup() { onMounted(() => { console.log('Component mounted to DOM'); // Perform initialization after mounting }); } }
Using onUnmounted
The onUnmounted hook is invoked when the component is about to be unmounted and destroyed. This is the perfect time to clean up, for example, by clearing timers or canceling external subscriptions.
javascriptimport { onUnmounted } from 'vue'; export default { setup() { onUnmounted(() => { console.log('Component about to be unmounted'); // Perform cleanup operations }); } }
Using onUpdated
The onUpdated hook triggers when the component's reactive dependencies change, leading to a re-render.
javascriptimport { onUpdated } from 'vue'; export default { setup() { onUpdated(() => { console.log('Component updated'); // Perform operations after DOM update }); } }
Example
Suppose we have a component that needs to fetch data from an API when the component loads and cancel any pending API requests before the component is unmounted. We can do this as follows:
javascriptimport { onMounted, onUnmounted } from 'vue'; import axios from 'axios'; export default { setup() { let cancelTokenSource = axios.CancelToken.source(); onMounted(async () => { try { const response = await axios.get('https://api.example.com/data', { cancelToken: cancelTokenSource.token }); console.log('Data: ', response.data); } catch (error) { if (axios.isCancel(error)) { console.log('Request canceled'); } else { console.error('Request error: ', error); } } }); onUnmounted(() => { cancelTokenSource.cancel('Component unmounted, cancel request'); }); } }
Through this example, we can see how to effectively utilize lifecycle hooks in the Composition API to manage and optimize component behavior.