Vue3 Parent component call child component method

Viewed 33

I can't call child component method in parent component in Vue3

In Vue2, I can call child component method like this

this.$root.$refs.ChildComponent.methodName()

But in Vue3, I receive a error like this

runtime-core.esm-bundler.js:218 Uncaught TypeError: Cannot read properties of undefined (reading 'methodName')
2 Answers

You might want to pass in a prop to the child, and react to a change-event by calling the method. This could look something like this:

<!-- Parent.vue -->
<script setup>
/* declare invokeChildMethod */
</script>

<template>
  <Child :prop="invokeChildMethod" /> 
</template>

As can be seen in the code below, when the variable (here called invokeChildMethod) changes (in the parent), an event for the child will be fired.

Here's a resource on watching props in Vue3.

defineExpose could do the magic. You could do something like this:

// in Parent
<template>
<ChildComponent ref="myChild"/>
</template>

<script>
const myChild = ref(null);

function() {
  myChild.childMethod();
}

</script>
// ChildComponent
<template> ... </template>
<script setup>

function childMethod() {
 // do something
}    

defineExpose({
        childMethod
    });
</script>
Related