我有一个 vue 游乐场。
容器组件需要能够控制默认槽中未知数量的children的显示状态。
我假设子组件需要持有一个属性或有某种方式向其容器标识自己。
容器如何更改默认槽中某个组件的显示属性?
应用程序.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>
容器.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>
您只需将引用添加到插槽的虚拟节点即可:
<script setup>
import { useSlots, ref, h} from 'vue'
const slots = useSlots();
let $children;
const slotted = () => ($children = [], slots.default().map((vnode, i) => h(vnode, {ref: $children[i] ??= ref()})));
function callInterfaceFunction(){
$children.forEach(({value: child}) => child.interfaceFunction());
}
</script>
<template>
<button @click="callInterfaceFunction">Call from Container</button>
<slotted/>
</template>