Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js: Is there a way to know when the component instance is mounted?

Tags:

vue.js

vuejs2

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>
like image 840
Julien Le Coupanec Avatar asked Nov 26 '25 10:11

Julien Le Coupanec


2 Answers

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
  }
}
like image 189
Roland Avatar answered Nov 30 '25 00:11

Roland


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");
  }
})
like image 39
Guru1988 Avatar answered Nov 29 '25 22:11

Guru1988