18

Is there a boolean we can access in each component instance to know when a component is mounted?

Something like:

<template>
  <div>
    <span v-if="$mounted">I am mounted</span>
    <span v-if="$created">I am created</span>
    <span>Called before created and mounted</span>
  </div>
</template>
Julien Le Coupanec
  • 7,742
  • 9
  • 53
  • 67
  • 1
    Sure. Use the `mounted` and `created` and `beforeCreate` functions natively supplied to you. Have a look at the [vue life-cycle diagram](https://vuejs.org/v2/guide/instance.html#Instance-Lifecycle-Hooks) – Ohgodwhy Mar 09 '19 at 17:29

2 Answers2

33

UPDATE 2020

There is an undocumented feature of Vue.js where you can know when a component's lifecycle hook is executed: Source.

The syntax is as follows:

<ChildComponent @hook:lifecycleHookName="callAMethod" />

Examples:

How to know when a child component is mounted:

<ChildComponent @hook:mounted="componentMountedDoSomething" />

How to know when a child component is created:

<ChildComponent @hook:created="componentCreatedDoSomething" />


<template>
  <div>
    <span v-if="mounted">I am mounted</span>
    <span v-if="created">I am created</span>
    <span>Called before created and mounted</span>
  </div>
</template>

And the script:

export default {
  data: () => ({
    created: false,
    mounted: false
  }),
  created () {
    this.created = true
  },
  mounted() {
    this.mounted = true
  }
}
kissu
  • 40,416
  • 14
  • 65
  • 133
Roland
  • 24,554
  • 4
  • 99
  • 97
  • 3
    Thank you this is what I was thinking. I was hoping Vue had a public boolean I could use to avoid these lines. :) – Julien Le Coupanec Mar 09 '19 at 17:56
  • Well it depends on what you are trying to achieve. Bc of the code above I am not understanding what you are trying to do. But there are not many lines there IMO. – Roland Mar 09 '19 at 18:00
  • 1
    There is but since it's not in the official docs it might not be the best way to rely on it. But if you examine the `VueInstance` object you'll find `_isMounted`, `_isBeingDestroyed`etc. booleans. `created` would be implicitly by the fact that there even is a vue instance available. – TommyF Mar 10 '19 at 10:09
  • How can one use this in JS? – Kalnode Aug 11 '22 at 15:18
2

Yes use lifecycle hooks.

new Vue({
  data: {
    a: 1
  },
  created() {
    // `this` points to the vm instance
    console.log('a is: ' + this.a)
  },
  mounted() {
    console.log("i am mounted in dom");
  }
})
kissu
  • 40,416
  • 14
  • 65
  • 133
Guru1988
  • 482
  • 3
  • 10