I have a parent component where I need to call a method that exists in one of its child components:
<template>
<div>
<button @click="callChildMethod">
<child-component ref="child" />
</div>
</template>
<script>
setup(props) {
const child = ref(null)
const callChildMethod = () => {
child.doSomething()
}
return {
child,
callChildMethod
}
}
</script>
The child component contains the doSomething
method:
const doSomething = () => { console.log('calling method....') }
Since I'm using the VueJS3 and the Composition API, my approach was to use a template ref to call the method in the child component. Obviously is not working but I can't see what I'm missing. Does someone have a clue about this one? Thanks in advance
P.s. for <script setup>
(Composition API)
need to use defineExpose
https://v3.vuejs.org/api/sfc-script-setup.html#defineexpose
Parent component:
<script setup>
...
const childred = ref();
childred.value.doSomething()
</script>
<template>
<ChildrenComponent ref="childred" />
</template>
ChildrenComponent:
<script setup>
...
function doSomething(){
console.log(1);
}
defineExpose({
doSomething,
});
</script>
<template>
<div>123</div>
</template>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With