Visiting the vue playground.
The main goal is for the container component to have control over an unspecified number of child components in the default slot.
In order to achieve this, it's assumed that each child component must either hold a property or identify itself to the parent container.
What would be the best approach for the container to modify the display property of a specific component within the default slot?
Please note there is a relevant query on How can a container change the CSS display property of a child in the default slots?, which focuses on using CSS as a solution to the same issue.
App.vue
<script setup>
import Container from './Container.vue'
import ChildA from './ChildA.vue'
import ChildB from './ChildB.vue'
</script>
<template>
<Container>
<ChildA />
<ChildB />
</Container>
</template>
Container.vue
<script setup>
import { useSlots, useAttrs, onMounted} from 'vue'
const slots = useSlots()
function logSlots(where) {
console.log( `${where} slots`, slots )
const children = slots.default()
console.log( `${where} slots children`, children.length, children )
}
logSlots("setup")
function changeDisplay(whichChild, show) {
console.log( "change display", whichChild, show)
// how can I know I am accessing child a?
// what goes here?
}
onMounted( () => {
logSlots("onMounted")
})
</script>
<template>
<button @click="logSlots('button')">log slots</button>
<button @click="changeDisplay('child a', false)">Hide Child A</button>
<button @click="changeDisplay('child a', true)">Show Child A</button>
<slot />
</template>
ChildA.vue
<script setup>
</script>
<template>
<div>
ChildA
</div>
</template>
ChildB.vue
<script setup>
</script>
<template>
<div>
ChildB
</div>
</template>