0

The structure of the app:

src/
|-- App.vue
|-- components/
    |-- MyComponent.vue
    |-- OtherComponent.vue

If I do, in MyComponent.vue

// MyComponent.vue

export default {
  name: 'MyComponent',
  methods: {
    mounted() {
      alert('MyComponent mounted')
    }
  }
}

This works as expected — an alert box is triggered when the component is mounted.

However, if I do the exact same thing in App.vue:

// App.vue

import MyComponent from './components/MyComponent.vue'
import OtherComponent from './components/OtherComponent.vue'

export default {
  name: 'app',
  components: {
    MyComponent,
    OtherComponent
  },
  methods: {
    mounted() {
      alert('app mounted')
    }
  }
}

Then nothing happens. I've tried with created, mounted, I've also try to wrap the alert() call into this.$nextTick({ ... }) — no success.

My problem is: I want something to happen (in this example, alert('app mounted')) once the child components have been mounted, because this "thing" needs to have all components mounted before executing.

Is it possible to hook a lifecycle event (ideally, mounted) in the App component?

Jivan
  • 21,522
  • 15
  • 80
  • 131

2 Answers2

1

All lifecycle methods need not to be declared within methods.

Should be as below.

// App.vue

import MyComponent from './components/MyComponent.vue'
import OtherComponent from './components/OtherComponent.vue'

export default {
  name: 'app',
  components: {
    MyComponent,
    OtherComponent
  },
   mounted() {
      alert('app mounted')
  },
  methods: {
  }
}

For more details read here

tony19
  • 125,647
  • 18
  • 229
  • 307
Riddhi
  • 2,174
  • 1
  • 9
  • 17
1

mounted is life cycle method of vue component. don't put it in methods.

Change

// MyComponent.vue

export default {
  name: 'MyComponent',
  methods: {
    mounted() {
      alert('MyComponent mounted')
    }
  }
}

To

// MyComponent.vue

export default {
  name: 'MyComponent',
  methods: {
  },
  mounted() {
    alert('MyComponent mounted')
  }
}
asissuthar
  • 2,078
  • 1
  • 15
  • 29