Composition API completely revamped the Options API with several improvements and changes. While these changes don’t affect the template scope much, we certainly have a lot to deal with what goes in the script.
One of such changes is how we use the lifecycle method in the Composition API.
Here’s what the lifecycle methods in the Options API used to look like:
<script>
export default {
mounted() {
console.log('mounted called!')
},
beforeMount() {
console.log('beforeMount called!')
},
destroyed() {
console.log('destroyed called!')
},
beforeDestroy() {
console.log('beforeDestroy called!')
},
}
</script>
Code language: HTML, XML (xml)
And here’s what the same would look like in the Composition API:
<script setup>
import { onMounted, onBeforeMount, onBeforeUnmount, onUnmounted } from "vue";
onMounted(() => {
console.log('onMounted called!')
})
onBeforeMount(() => {
console.log('onBeforeMount called!')
})
onBeforeUnmount(() => {
console.log('onBeforeUnmount called!')
})
onUnmounted(() => {
console.log('onUnmounted called!')
})
</script>
Code language: HTML, XML (xml)
What’s worth noting is that, with the Composition API, we can now group relevant parts of the code easily. That is, we had to use the mounted hook to mount all the unrelated logic at once in the Options API:
mounted() {
this.getUsersList()
this.getUsersData()
this.getAllPosts()
this.getPostsData()
this.getComments()
this.getCommentsData()
// ...and more
}
Code language: JavaScript (javascript)
Instead of doing that, we can now group relevant parts of the code and have multiple hooks for them:
// users
onMounted(() => {
this.getUsersList()
this.getUsersData()
})
// posts
onMounted(() => {
this.getAllPosts()
this.getPostsData()
})
// comments
onMounted(() => {
this.getComments()
this.getCommentsData()
})
Code language: JavaScript (javascript)
We can apply the same idea to other lifecycle methods as well.