📜 ⬆️ ⬇️

Hooks life cycle Vue.js


Lifecycle hooks are an important part of any serious component. We often need to know when a component was created, added to the DOM, updated or destroyed. Life cycle hooks show us how the selected library works behind the scenes. They often cause trepidation or anxiety in newbies. Fortunately, it is easy to understand how the hooks work, see the diagram:



Creation (initialization)


First in your component are the creation hooks . They allow you to perform actions even before the component is added to the DOM. Unlike others, creation hooks are also performed during server-side rendering.


Use creation hooks when you need to; you need to configure something in the component during rendering on the client and server side. Inside these hooks, you will not have access to the DOM or target element (mounting element) ( this.$el ).


beforeCreate


The beforeCreate is executed directly during component initialization. Data has not yet become reactive, and events are not configured.


Example:


 ExampleComponent.vue <script> export default { beforeCreate() { console.log('Nothing gets called before me!') } } </script> 

created


In the created hook you can get access to reactive data and active events. Templates and virtual DOM are not yet built (mounted) and not drawn.


Example:


 ExampleComponent.vue <script> export default { data() { return { property: 'Blank' } }, computed: { propertyComputed() { console.log('I change when this.property changes.') return this.property } }, created() { this.property = 'Example property update.' console.log('propertyComputed will update, as this.property is now reactive.') } } </script> 

Embedding (insertion into DOM)


Installation hooks are one of the most commonly used. They allow you to access the component immediately before or immediately after the first drawing. However, these hooks are not executed during the rendering on the server side.


Use them if you need to edit the DOM of the component or access it immediately before the initial rendering or immediately after it.


Do not use these hooks if you need to extract data for a component during initialization. In this case, use created (or created + activated for keep-alive components), especially if you need this data during the rendering on the server side.


beforeMount


The beforeMount is executed before the primary rendering, as well as after compiling the template or the drawing functions. You probably never need to use this hook. Remember that it is not called during server-side rendering.


Example:


 ExampleComponent.vue <script> export default { beforeMount() { console.log(`this.$el doesn't exist yet, but it will soon!`) } } </script> 

mounted


In the mounted hook, you will get full access to the reactive component, the templates, and the DOM drawn (via this.$el ). Mounted is the most popular lifecycle hook. Usually it is used to extract data for a component (use created instead) and DOM changes, often to integrate non-Vue libraries.


Example:


 ExampleComponent.vue <template> <p>I'm text inside the component.</p> </template> <script> export default { mounted() { console.log(this.$el.textContent) // I'm text inside the component. } } </script> 

Update (diffs and redraw)


Update hooks are called when the reactive property used by your component has changed, or when something else causes a redraw. These hooks allow you to access the component's “track-calculate-draw” cycle.


Use them if you need to learn about component redrawing, for example, for debugging or profiling.


Do not use them if you need to know about a change in a reactive property in a component; instead, use computed properties or “ watchers ”.


beforeUpdate


The beforeUpdate is executed after changing the data in the component and starting the update cycle, immediately before patching and redrawing the DOM. This hook allows you to get a new state of any reactive data in the component before it is drawn.


Example:


 ExampleComponent.vue <script> export default { data() { return { counter: 0 } }, beforeUpdate() { console.log(this.counter) // Logs the counter value every second, before the DOM updates. }, created() { setInterval(() => { this.counter++ }, 1000) } } </script> 

updated


The updated hook is called after changing the data in the component and redrawing the DOM. If you need to access the DOM after a property change, such a hook is the safest place to do this.


Example:


 ExampleComponent.vue <template> <p ref=”dom-element”>{{counter}}</p> </template> <script> export default { data() { return { counter: 0 } }, updated() { // Fired every second, should always be true console.log(+this.$refs['dom-element'].textContent === this.counter) }, created() { setInterval(() => { this.counter++ }, 1000) } } </script> 

Destruction


Destruction hooks allow you to act, for example, to tidy up or send data for analytics, after the destruction of the component. These hooks are triggered when the element is removed and removed from the DOM.


beforeDestroy


beforeDestroy is executed immediately before installation. Your component is still fully functional. If you need to clear events or reactive subscriptions, beforeDestroy is the right place for it.


Example:


 ExampleComponent.vue <script> export default { data() { return { someLeakyProperty: 'I leak memory if not cleaned up!' } }, beforeDestroy() { // Perform the teardown procedure for someLeakyProperty. // (In this case, effectively nothing) this.someLeakyProperty = null delete this.someLeakyProperty } } </script> 

destroyed


By the time you got to the hook destroyed , there was little left of your component. Everything that has been attached to it has already been destroyed. You can use the hook for the last cleanup, or, like a sneaky softball, inform the remote server about the destruction of the component. <_<


Example:


 ExampleComponent.vue <script> import MyCreepyAnalyticsService from './somewhere-bad' export default { destroyed() { console.log(this) // There's practically nothing here! MyCreepyAnalyticsService.informService('Component destroyed. All assets move in on target on my mark.') } } </script> 

Other hooks


There are two other hooks, activated and deactivated . They are already designed for keep-alive components that are beyond the scope of this article. Suffice it to say that these hacks allow you to determine whether a component wrapped in <keep-alive></keep-alive> tags is included. You can use them to extract data for a component or handle state changes. These hacks will behave as created and beforeDestroy , but without the need to completely reassemble the component.


')

Source: https://habr.com/ru/post/350962/


All Articles