Exploring the realms of a vue playground.
The functions interfaceFunction
in both ChildA
and ChildB
are exposed.
In App
, these functions can be called by obtaining references to the components that expose them. This allows direct function calls from within App
.
For Container
to access and call these functions from its children in the default slot, how can it obtain references to the components and invoke the functions?
Code snippet from 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>
Code snippet from 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>
Code snippet from ChildA.vue:
<script setup>
function interfaceFunction() {
console.log( "Called interfaceFunction A" )
}
defineExpose({ interfaceFunction })
</script>
<template>
<div>
ChildA
</div>
</template>
Code snippet from ChildB.vue:
<script setup>
function interfaceFunction() {
console.log( "Called interfaceFunction A" )
}
defineExpose({ interfaceFunction })
</script>
<template>
<div>
ChildB
</div>
</template>