Senior
How to call a child component's method from a parent component in Vue.js?
sobes.tech AI
Answer from AI
In Vue.js (versions 2 and 3), to call a child component's method from a parent, you can use a reference to the component via ref.
Example:
<!-- Parent component -->
<template>
<ChildComponent ref="child" />
<button @click="callChildMethod">Call child method</button>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: { ChildComponent },
methods: {
callChildMethod() {
this.$refs.child.someMethod();
}
}
}
</script>
<!-- Child component -->
<template>
<div>Child component</div>
</template>
<script>
export default {
methods: {
someMethod() {
console.log('Child component method called');
}
}
}
</script>
Explanation:
- In the parent template, the child component has a
refattribute. - In the parent's methods, you can access the child component instance via
this.$refs.child. - Then, you can call the desired method of the child component.
Important: ref is only available after the component has been mounted, so the call should happen after that (e.g., in an event handler or in mounted).