Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue3 Parent component call child component method

Tags:

vuejs3

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')
like image 274
Khang Avatar asked Dec 11 '25 01:12

Khang


1 Answers

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

Parent

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

<script>
const myChild = ref(null);

function() {
  myChild.value.childMethod();
}
</script>

Child Component

<template>
  ...
</template>

<script setup>
function childMethod() {
 // do something
}    

defineExpose({
  childMethod
});
</script>
like image 144
nocrash9000 Avatar answered Dec 14 '25 19:12

nocrash9000



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!