Vue.js Lifecycle Hooks

Original author: Joshua Bemenderfer
  • Transfer


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. Lifecycle hooks show us how the selected library works behind the scenes. They often cause novice anxiety or anxiety. Fortunately, it’s easy to understand how hooks work, see the diagram:



Creation (initialization)


First in your component are 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 configure something in a component during rendering on the client and server side. Inside these hooks, you will not have access to the DOM or the target element (mounting element) ( this.$el ).


beforeCreate


The hook beforeCreate executes 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 a hook, created you can access reactive data and active events. Templates and the virtual DOM are not yet mounted or mounted.


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 (DOM Paste)


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


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


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


beforeMount


The hook beforeMount is executed before the initial rendering, and also after compiling the template or rendering 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 hook, mounted you get full access to the reactive component, templates, and the rendered DOM (via this.$el ). Mounted - The most popular lifecycle hook. It is usually used to extract data for a component (use it instead created ) and modify the DOM, often for the sake of integrating 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 redrawing)


Update hooks are called when the reactive property used by your component changes, or when something else leads to a redraw. These hooks allow you to access the component’s “tracking-computing-rendering” 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 calculated properties or “ watchers ”.


beforeUpdate


The hook beforeUpdate is executed after changing the data in the component and the start of the update cycle, immediately before patching and redrawing the DOM. This hook allows you to get the 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 hook updated is called after changing the data in the component and redrawing the DOM. If you need to access the DOM after changing a property, 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 fire when a member is removed and removed from the DOM.


beforeDestroy


beforeDestroy performed immediately before installation. Your component is still fully operational. If you need to clear events or reactive subscriptions, then this beforeDestroy is the most suitable place for this.


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 get to the hook destroyed , little is left of your component. Everything that was attached to it has already been destroyed. You can use the hook for the last cleanup or, like a sneaky quiet guy, 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 intended 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 tags is included <keep-alive></keep-alive> . You can use them to retrieve data for a component or process state changes. These hacks will behave as created and beforeDestroy without the need to completely reassemble the component.