I have child components within a slot in a parent component and I am trying to call methods on them. Here are the steps I followed:
- Use
useSlots
to retrieve the child components as objects - Expose the method in the child component using
defineExpose
- Call the method on the child component objects
However, I noticed that the method is not present on the object as expected.
For example:
// Parent.vue
<template>
<div><slot/></div>
</template>
<script lang="ts" setup>
const slots = useSlots() as any;
const children = slots.default();
function callMethods() {
console.log(children);
}
</script>
// SomeComponent.vue
<template>
// ...
</template>
<script lang="ts" setup>
// ...
function methodToBeCalledByParent() {
console.log(123);
}
defineExpose({
methodToBeCalledByParent
});
</script>
In another part of the code, I placed this snippet:
<parent>
<some-component/>
<some-component/>
</parent>
Goal: Enable the callMethods
function to call methodToBeCalledByParent
in each respective some-component
through the children
object.
When the callMethods
function is executed, there should be an array of two some-component
instances printed in the console. However, the content of each child does not seem right, with many occurrences of null
. Most importantly, the exposed methodToBeCalledByParent
cannot be found in the object.
https://i.sstatic.net/E8I8GaZP.png
I have researched online and learned that the method can be called directly once the component object is retrieved. So I am unsure where the issue lies in my code. Can someone suggest the correct (or better) way to achieve this functionality?