Luca Spezzano
Luca Spezzano

Reputation: 380

Vue.js lifecycle hooks

I was sure that the lifecycle hooks in Vue were 8 (beforeCreate, created, beforeMount, mounted, beforeUpdate, updated, beforeDestroy, destroyed) but today I found out(https://v2.vuejs.org/v2/api/#activated) that there are 3 more:

activated

deactivated

error captured

Somebody can explain how these 3 work? Is possible to test them with a console.log? (Just to understand when they are called)

Upvotes: 1

Views: 3996

Answers (2)

Buns of Aluminum
Buns of Aluminum

Reputation: 2439

First, a little context:

In Vue 2.0+, there is a built-in component called <keep-alive> that takes the child element inside it and keeps it alive in memory as a cached component. Normally, Vue would reuse a component if its props change, but maybe the component is very complex and is slow to update. You could wrap it with <keep-alive> and the component would be cached for the props provided to it.

When a component inside a <keep-alive> is updated, the activated life-cycle hook is called. When that component is cached and set aside, the deactivated life-cycle hook is called.

The errorCaptured life-cycle hook was added in Vue 2.5.0 and is called whenever an error is captured by a descendent component. So, if you have a component called A that has a child component called B, and that has a child component called C, then if C captures and error, the errorCaptured life-cycle hook will be called on both A and B.

These hooks all work the same as any other hook, so use them the same way.

export default {
    data() {
      return {}
    },
    mounted() {
      console.log('mounted hook called')
    },
    errorCaptured(err, vm, info) {
      console.log('error captured in component', vm)
      console.error(err)
      console.log('error info:', info)
    },
    activated() {
      console.log('cached component is being used again')
    },
    deactivated() {
      console.log('component is being kept alive in cache for now')
    }
}

Upvotes: 4

xreyc
xreyc

Reputation: 221

I know it's already late for this answer but someone might also looking answer for the problem. Vue.js disable's console.log function by default, so we have to enable it.

Just put "rules": { "no-console": "off",} on package.json

Cheers

Upvotes: 1

Related Questions