Lifecycle Hooks - sikaeducation/vue-curriculum GitHub Wiki
There are technically 8 lifecycle hooks in Vue:
beforeCreatecreatedbeforeMountmountedbeforeUpdateupdatedbeforeUnmountunmounted
These describe moments in the "lifecycle" of a Vue component that you can "hook" into.
In practice, the only one you're likely to need in most circumstances is created. This is where fetches that should fire off as soon as a component loads go, and most other setup tasks.
These methods already exist on every Vue component, so you're just overriding them when you declare them on a component. They go at the same level as data(), components, methods, and props:
<script>
export default {
data() {
pokemon: [],
},
created() {
fetch("https://pokeapi.co/api/v2/pokemon")
.then(response => response.json())
.then(response => {
this.pokemon = response.results
})
},
}
</script>Inside of lifecycle hooks, you can access state, computed properties, methods, and props.
- When a component is
mounted, the DOM is available -
updatedandbeforeUpdatecan be used to slow down how often a component is rerendering, even if the data is reacting much faster -
unmountedis used to clean up things like timers or things that might leak memory over time