0
0
Vueframework~5 mins

onMounted and onUnmounted in Vue - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the onMounted lifecycle hook do in Vue 3?
It runs a function right after the component is added to the page (DOM). Think of it like saying "Hey, I am ready now!"
Click to reveal answer
beginner
When is the onUnmounted hook called in a Vue component?
It runs a function just before the component is removed from the page. It's like cleaning up your desk before leaving.
Click to reveal answer
beginner
How do you import <code>onMounted</code> and <code>onUnmounted</code> in Vue 3 Composition API?
You import them from 'vue' like this: <br><code>import { onMounted, onUnmounted } from 'vue'</code>
Click to reveal answer
intermediate
Why is onUnmounted useful in Vue components?
It helps you stop timers, remove event listeners, or clean resources so your app stays fast and tidy.
Click to reveal answer
intermediate
Show a simple example of using onMounted and onUnmounted in a Vue component.
Example:<br><pre>import { ref, onMounted, onUnmounted } from 'vue'

export default {
  setup() {
    const count = ref(0)
    let timer

    onMounted(() => {
      timer = setInterval(() => {
        count.value++
      }, 1000)
    })

    onUnmounted(() => {
      clearInterval(timer)
    })

    return { count }
  }
}</pre>
Click to reveal answer
What is the main purpose of onMounted in Vue 3?
ARun code after the component appears on the page
BRun code before the component is created
CRun code when the component is destroyed
DRun code before the component appears on the page
Which hook should you use to clean up timers or event listeners in Vue 3?
AonUnmounted
BonMounted
ConCreated
DonUpdated
How do you import onMounted in a Vue 3 component?
Aimport { onMounted } from 'vue-router'
Bimport { onMounted } from 'vue'
Cimport onMounted from 'vue'
Dimport onMounted from 'vue-router'
When does onUnmounted run in the component lifecycle?
ARight after the component is mounted
BBefore the component is mounted
CBefore the component is removed from the DOM
DAfter the component updates
Which of these is a good use case for onMounted?
AStopping a timer when the component disappears
BRemoving event listeners
CResetting component data before removal
DStarting a timer when the component appears
Explain in your own words what onMounted and onUnmounted hooks do in Vue 3.
Think about when you start and stop something when entering or leaving a room.
You got /3 concepts.
    Describe a practical example where you would use both onMounted and onUnmounted in a Vue component.
    Imagine turning on a light when you enter a room and turning it off when you leave.
    You got /3 concepts.