Every Vue component goes through a number of steps to initialize it when it's created. Among other things, these steps are responsible for compiling and rendering the HTML template, setting up the component's data so it becomes reactive, and mounting the component into the DOM. In order to hook into this process, we're given a number of lifecycle hooks that we can use to run our own application-specific initialization code at each stage.
These lifecycle hooks are as follows, and named appropriately enough to make themselves fairly self-explanatory:
- beforeCreate
- created
- beforeMount
- mounted
- beforeUpdate
- updated
- beforeDestroy
- destroyed
beforeUpdate and updated run in a continuous loop for the duration of the component's lifetime. Every time Vue detects a data change within the component, these steps are run before and after the virtual DOM is re-rendered.
So, how do we actually make use of these function hooks? The following code shows an example of how we declare the hooks we wish to use within a component definition:
<script>
export default {
name: 'lifecycle-hooks',
beforeCreate () {
console.log('before create')
},
created () {
console.log('created')
},
beforeMount () {
console.log('before mount')
},
mounted () {
console.log('mounted')
},
beforeUpdate () {
console.log('before update')
},
updated () {
console.log('updated')
},
beforeDestroy () {
console.log('before destroy')
},
destroyed () {
console.log('destroyed')
}
}
</script>
We simply add a root-level function with its key matching the name of the lifecycle hook we want to use. This is all very well and good, but if you've never used an SPA framework such as Vue before, you're probably wondering why we'd ever want to bother doing this. There are many reasons to use lifecycle hooks, the most common of which is probably to fetch the data the component needs from an API somewhere. A good place to do this is in the created hook because we don't need access to the DOM, so there is no need to wait until the mounted hook is run later. The other reason to use created instead of mounted is because created is the only hook that is run on both client- and server-rendered versions of the component. We'll look at server-side rendering in one of the final chapters in this book!
A few other examples include triggering animations as soon as the page is displayed, and dirty checking a form to give the user a chance to complete it before navigating away. We would need to use the mounted and beforeDestroy hooks for these actions, respectively.
So far, we've been focusing on the Vue instances and the different ways they help us manage the data that our components are responsible for, but this is only half of the story. We're yet to see how Vue can help us actually display that data. Let's start focusing on the template section of our components!