onMounted hook runs?Consider this Vue 3 composable using onMounted:
import { ref, onMounted } from 'vue'
export function useTimer() {
const count = ref(0)
onMounted(() => {
count.value = 5
})
return { count }
}If a component uses useTimer(), what will count.value be immediately after the component mounts?
Remember that onMounted runs after the component is mounted, so the value changes then.
The onMounted hook runs after the component is mounted, setting count.value to 5. So after mounting, count.value is 5.
message after the composable's onUnmounted hook runs?Given this composable:
import { ref, onUnmounted } from 'vue'
export function useMessage() {
const message = ref('Hello')
onUnmounted(() => {
message.value = 'Goodbye'
})
return { message }
}If a component uses useMessage() and then unmounts, what will message.value be?
Think about when onUnmounted runs and if state can be changed then.
The onUnmounted hook runs just before the component is removed. It changes message.value to 'Goodbye'. So after unmounting, message.value is 'Goodbye'.
onBeforeUnmount inside a composable?Choose the option that correctly registers a cleanup function with onBeforeUnmount in a Vue 3 composable.
Remember onBeforeUnmount is a function you call with a callback.
Option B correctly calls onBeforeUnmount with a callback function. Option B tries to assign to onBeforeUnmount, which is invalid. Option B calls the result of onBeforeUnmount, which is not a function. Option B has a syntax error (missing closing parenthesis).
onMounted hook not run?Look at this composable:
import { ref, onMounted } from 'vue'
export function useData() {
const data = ref(null)
onMounted(() => {
data.value = 'Loaded'
})
return { data }
}But when used in a component, data.value stays null. What is the likely cause?
Lifecycle hooks only work inside component setup or other lifecycle hooks.
If the composable is called outside the component's setup function, Vue does not run lifecycle hooks like onMounted. So data.value stays null.
Why do Vue developers use lifecycle hooks like onMounted inside composables instead of only inside components?
Think about how composables help organize code.
Using lifecycle hooks inside composables lets developers share code that depends on component lifecycle events, making code reusable and cleaner.