0
0
Vueframework~10 mins

Composable with lifecycle hooks in Vue - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the lifecycle hook for setup.

Vue
import { [1] } from 'vue';
Drag options to blanks, or click blank then click option'
Amounted
BonMounted
CcomponentDidMount
DuseEffect
Attempts:
3 left
💡 Hint
Common Mistakes
Using React lifecycle hooks like useEffect in Vue code.
Trying to import 'mounted' which is not a function.
2fill in blank
medium

Complete the code to define a composable that logs a message when mounted.

Vue
export function useLogger() {
  [1](() => {
    console.log('Component mounted');
  });
}
Drag options to blanks, or click blank then click option'
AonCreated
BuseEffect
Cmounted
DonMounted
Attempts:
3 left
💡 Hint
Common Mistakes
Using mounted as a function instead of a hook.
Confusing Vue hooks with React hooks.
3fill in blank
hard

Fix the error in the composable to clean up on unmount.

Vue
import { onMounted, [1] } from 'vue';

export function useTimer() {
  let timer;
  onMounted(() => {
    timer = setInterval(() => console.log('tick'), 1000);
  });
  [1](() => {
    clearInterval(timer);
  });
}
Drag options to blanks, or click blank then click option'
AonUnmounted
BonDestroy
CbeforeUnmount
DonCleanup
Attempts:
3 left
💡 Hint
Common Mistakes
Using onDestroy which is not a Vue hook.
Trying to use beforeUnmount without importing it.
4fill in blank
hard

Fill both blanks to create a composable that tracks window width and cleans up on unmount.

Vue
import { ref, [1], [2] } from 'vue';

export function useWindowWidth() {
  const width = ref(window.innerWidth);

  function updateWidth() {
    width.value = window.innerWidth;
  }

  [1](() => {
    window.addEventListener('resize', updateWidth);
  });

  [2](() => {
    window.removeEventListener('resize', updateWidth);
  });

  return width;
}
Drag options to blanks, or click blank then click option'
AonMounted
BonUnmounted
Cwatch
DonUpdated
Attempts:
3 left
💡 Hint
Common Mistakes
Using watch instead of lifecycle hooks for event listeners.
Forgetting to remove the event listener on unmount.
5fill in blank
hard

Fill all three blanks to create a composable that logs on mount, updates a count on button click, and cleans up on unmount.

Vue
import { ref, [1], [2], onUnmounted } from 'vue';

export function useCounter() {
  const count = ref(0);

  [1](() => {
    console.log('Counter mounted');
  });

  function increment() {
    count.value++;
  }

  [3](() => {
    console.log('Counter unmounted');
  });

  return { count, increment };
}
Drag options to blanks, or click blank then click option'
AonMounted
BonUpdated
ConUnmounted
Dwatch
Attempts:
3 left
💡 Hint
Common Mistakes
Not importing all lifecycle hooks.
Using watch instead of onUpdated for update lifecycle.