Hone logo
Hone
Problems

Implementing the onMounted Hook in Vue.js (TypeScript)

This challenge focuses on understanding and implementing the onMounted lifecycle hook in Vue.js using TypeScript. The onMounted hook is crucial for performing side effects after a component has been mounted to the DOM, such as fetching data, initializing third-party libraries, or setting up event listeners. Mastering this hook is fundamental for building interactive and data-driven Vue applications.

Problem Description

Your task is to create a Vue.js component that demonstrates the correct usage of the onMounted hook. The component should have a simple counter that increments every second after the component has been mounted to the DOM.

Key Requirements:

  1. Vue Component Structure: Create a functional Vue component using the Composition API.
  2. onMounted Usage: Implement the onMounted hook within the setup function of the component.
  3. Counter Logic: Inside the onMounted hook, set up an interval that increments a reactive counter variable every 1000 milliseconds (1 second).
  4. Display Counter: Display the current value of the counter in the component's template.
  5. Cleanup: Crucially, ensure that the interval is cleared when the component is unmounted to prevent memory leaks. This should also be handled within the onMounted hook's returned cleanup function.
  6. TypeScript: All code should be written in TypeScript.

Expected Behavior:

  • When the component is rendered, the counter should initially display 0.
  • Immediately after the component is mounted to the DOM, the counter should start incrementing every second.
  • If the component is removed from the DOM, the interval should stop, and the counter should cease incrementing.

Edge Cases to Consider:

  • Component Unmount: What happens if the component is removed from the DOM before the interval has a chance to run a few times? The cleanup mechanism should handle this gracefully.

Examples

Example 1: Initial State and Mounting

<script setup lang="ts">
import { ref, onMounted } from 'vue';

const count = ref(0);
let intervalId: number | null = null; // Type annotation for interval ID

onMounted(() => {
  console.log('Component mounted!');
  intervalId = setInterval(() => {
    count.value++;
    console.log(`Count incremented to: ${count.value}`);
  }, 1000);
});

// This component's template would display the count
// For demonstration, we'll assume this part is handled by the template.
</script>

<template>
  <div>
    <p>Counter: {{ count }}</p>
  </div>
</template>

Explanation:

When this component mounts, onMounted is executed. It logs a message, then starts an interval that increments count.value every second. The template then displays the reactive count.

Example 2: Component Unmounting

Imagine the component from Example 1 is being displayed within another component that conditionally renders it. When the condition becomes false and the component is removed:

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'; // Added onUnmounted for clarity

const count = ref(0);
let intervalId: number | null = null;

onMounted(() => {
  console.log('Component mounted!');
  intervalId = setInterval(() => {
    count.value++;
    console.log(`Count incremented to: ${count.value}`);
  }, 1000);

  // Cleanup function returned by onMounted
  return () => {
    if (intervalId !== null) {
      clearInterval(intervalId);
      console.log('Interval cleared on component unmount.');
    }
  };
});

// A more explicit cleanup can also be done with onUnmounted
// onUnmounted(() => {
//   if (intervalId !== null) {
//     clearInterval(intervalId);
//     console.log('Interval cleared via onUnmounted.');
//   }
// });
</script>

<template>
  <div>
    <p>Counter: {{ count }}</p>
  </div>
</template>

Explanation:

When the component is removed from the DOM, the cleanup function returned by onMounted (or the onUnmounted hook if used explicitly) is automatically called by Vue. This function checks if intervalId exists and clears the interval, preventing the counter from continuing to increment in the background. The console logs would confirm that the interval has been cleared.

Constraints

  • The solution must use Vue 3.
  • The solution must be written entirely in TypeScript.
  • The interval must be set to increment the counter every 1000 milliseconds.
  • Memory leaks must be avoided by properly clearing the interval.
  • The solution should be a single, self-contained .vue file.

Notes

  • The onMounted hook is designed for actions that require access to the DOM. Consider what would happen if you tried to access DOM elements before onMounted executes.
  • Vue provides onUnmounted as a separate hook for cleanup, but onMounted's returned function is the idiomatic way to handle cleanup for setup logic initiated within onMounted.
  • Pay close attention to the type of the intervalId when using setInterval in TypeScript.
  • You will need to define a reactive variable to hold the counter's value.
Loading editor...
typescript