Vue3 Fundamentals · Composition & Reuse

Lifecycle hooks

Lifecycle hooks

Some work can only run once the component is on the page: measuring an element, starting a timer, fetching data. In <script setup> the body runs while the component is being created, before its DOM exists.

Vue calls lifecycle hooks at known moments. onMounted runs after the component's DOM has been inserted:

<script setup>
import { onMounted, ref } from 'vue';

const status = ref('loading');

onMounted(() => {
  status.value = 'ready';
});
</script>

The callback runs once, after mount. Changing a ref inside it triggers a re-render, so the template can show the new value. Other hooks cover other moments — onUpdated, onUnmounted — but the shape is the same: register a callback, and Vue calls it at the right time.

The Test mounts your component and waits a tick for the mount to finish. It checks that the status reads ready. The starter never registers a hook, so the status stays loading and the Test fails. Set the value from onMounted in App.vue.

Challenge

The status is stuck on loading because nothing runs after the component mounts. Export an App component from App.vue that registers an onMounted hook setting a status ref to ready, and renders the status in a <p>.

The Test mounts your component, waits a tick, and checks the paragraph reads ready. The starter registers no hook, so the status stays loading and the Test fails. Set it from onMounted.

App.vue
<script setup>
import { ref } from 'vue';

const status = ref('loading');
</script>

<template>
  <p>{{ status }}</p>
</template>

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.