I have a vue playground.
ChildA
and ChildB
both expose a function called interfaceFunction
.
I can call this function from App
by getting a reference to the component. With the reference, I can call the function directly.
I would like Container
to be able to call this function of the children in its default slot. How can Container
get a reference to the components and call the function?
App.vue
<script setup>
import { ref} from 'vue'
import Container from './Container.vue'
import ChildA from './ChildA.vue'
import ChildB from './ChildB.vue'
const childa = ref(null)
function callInterfaceFunction() {
childa.value.interfaceFunction()
}
</script>
<template>
<button @click="callInterfaceFunction">Call from App</button>
<Container>
<ChildA ref="childa"/>
<ChildB />
</Container>
</template>
Container.vue
<script setup>
import { useSlots} from 'vue'
const slots = useSlots()
function callInterfaceFunction() {
const children = slots.default()
for ( const child of children ) {
child.interfaceFunction()
}
}
</script>
<template>
<button @click="callInterfaceFunction">Call from Container</button>
<slot />
</template>
ChildA.vue
<script setup>
function interfaceFunction() {
console.log( "Called interfaceFunction A" )
}
defineExpose({ interfaceFunction })
</script>
<template>
<div>
ChildA
</div>
</template>
ChildB.vue
<script setup>
function interfaceFunction() {
console.log( "Called interfaceFunction A" )
}
defineExpose({ interfaceFunction })
</script>
<template>
<div>
ChildB
</div>
</template>