Vue — Lifecycle
Lifecycle hooks
<script>
export default {
beforeCreate() {
console.log('beforeCreate')
},
created() {
console.log('created')
},
beforeMount() {
console.log('beforeMount')
},
mounted() {
console.log('mounted')
},
beforeUpdate() {
console.log('beforeUpdate')
},
updated() {
console.log('updated')
},
beforeUnmount() {
console.log('beforeUnmount')
},
unmounted() {
console.log('unmounted')
}
}
</script>
Lifecycle diagram
beforeCreate
↓
created
↓
beforeMount
↓
mounted
↓
beforeUpdate
↓
updated
↓
beforeUnmount
↓
unmounted
Common uses
<script>
export default {
created() {
// Fetch data when component is created
this.fetchData()
},
mounted() {
// Access DOM after rendering
this.$refs.input.focus()
},
beforeUnmount() {
// Cleanup timers, listeners
clearInterval(this.timer)
}
}
</script>
Composition API lifecycle
<script setup>
import { onMounted, onUnmounted } from 'vue'
onMounted(() => {
console.log('Mounted!')
fetchData()
})
onUnmounted(() => {
console.log('Unmounted!')
})
</script>
Error handling
<script>
export default {
errorCaptured(err, instance, info) {
console.error('Error:', err)
return false // Prevent error propagation
}
}
</script>
Mini Practice
- Log each lifecycle hook
- Fetch data in created
- Access DOM in mounted
- Clean up in beforeUnmount
Up Next
Continue with Reactivity - Vue's reactivity system.
Related Topics
Frequently Asked Questions about Lifecycle
What is Lifecycle in Vue?
Lifecycle is a fundamental concept in Vue. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Lifecycle?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Lifecycle.
Why is Lifecycle important in Vue?
Lifecycle is essential for Vue development. Understanding this concept will help you write better code and solve real-world problems more effectively.