I want to check if child component is mounted and I want to move that information to he parent component. For this I am using emits. So with example here is my parent component:
<child @is-child-mounted="childMounted" />
export default {
data() {
return {
childMounted: false,
};
},
mounted() {
if (this.childMounted) {
//do something
}
},
}
and in child component, I am changing 'is-child-mounted' to true:
mounted() {
this.$emit('isChildMounted', true);
},
But still if (this.childMounted) comes false. So how can I check in parent component if the child component is mounted?
CodePudding user response:
You can add a listener on the child component fom the parent. It would look like this:
Vue3
<Component
@vnodeMounted="handleMounted"
/>
Vue2
<Component
@hook:mounted="handleMounted"
/>
You can replace the hook name by the lifecycle one you want to listen to ! I guess it should be used sparsely as it is not present in the documentation and thus be an internal API that is not destined to be used directly.
source:
- https://github.com/vuejs/core/issues/4345#issuecomment-899082892
- https://github.com/vuejs/vue/blob/8d3fce029f20a73d5d0b1ff10cbf6fa73c989e62/src/core/instance/lifecycle.js#L348
CodePudding user response:
Looks like there is a typo in the event name in the child component while triggering the event else code should work fine.
- It should be
is-child-mounted
instead ofischildmounted
- It should be
@is-child-mounted="childMounted = true"
instead of@is-child-mounted="childMounted"
Live Demo :
Vue.component('child', {
props: ['childmsg'],
template: '<p>{{ childmsg }}</p>',
mounted() {
this.$emit('is-child-mounted')
}
});
var app = new Vue({
el: '#app',
data: {
childMounted: false
},
mounted() {
if (this.childMounted) {
console.log('child mounted');
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<child childmsg="This is a child component" @is-child-mounted="childMounted = true"></child>
</div>