Today we will learn about lifecycle methods in Nuxt.js
Nuxt Lifecycle:
No matter that tool you utilize, you’ll forever feel additional assured after you perceive however the tool works underneath the hood. identical applies to Nuxt.
Lifecycle methods:
- asyncData()
- beforeCreate()
- created()
- fetch()
- mounted()
1. asyncData():
- asyncData is another hook for universal information winning. in contrast to fetch, which needs you to line properties on the element instance (or dispatch Vuex actions) to avoid wasting your async state, asyncData simply merges its come back price into your component’s native state.
- Here’s associate degree example exploitation the @nuxt/http library:
<template> <div> <h1>{{ post.title }}</h1> <p>{{ post.description }}</p> </div> </template> <script> export default { async asyncData({ params, $http }) { const post = await $http.$get(`https://api.nuxtjs.dev/posts/${params.id}`) return { post } } } </script>
2. beforeCreate():
- Called synchronously in real time when the instance has been initialized, before knowledge observation and event/watcher setup.
3. created():
- Called synchronously once the instance is made. At this stage, the instance has finished process the choices which suggests the subsequent are set up: information observation, computed properties, methods, watch/event callbacks. However, the mounting part has not been started, and therefore the $el property won’t be on the market nonetheless.
4. fetch():
-
fetch is a hook called during server-side rendering after the component instance is created, and on the client when navigating. The fetch hook should return a promise (whether explicitly, or implicitly using async / await) that will be resolved:
- On the server, before the initial page is rendered
- On the client, some time after the component is mounted
5. mounted():
- Called once the instance has been mounted, wherever component, passed to app.mount is replaced by the fresh created vm.$el. If the foundation instance is mounted to associate degree in-document component, vm.$el also will be in-document once mounted is termed.
- Note that mounted doesn’t guarantee that each one kid elements have conjointly been mounted. If you wish to attend till the complete read has been rendered, you’ll use vm.$nextTick within mounted:
mounted() { this.$nextTick(function () { // Code that will run only after the // entire view has been rendered }) }