容器如何更改默认插槽中子级的 CSS 显示属性?

问题描述 投票:0回答:1

我有一个 vue 游乐场

容器组件需要能够控制默认插槽中未知数量的子组件的 CSS 显示属性。

我假设子组件需要持有一个属性或有某种方式向其容器标识自己。

容器如何更改默认插槽中组件之一的 CSS 显示属性?

理想情况下,用于操作 CSS 显示属性的技术可以用于操作其他 CSS 属性。

注意,有一个相关问题容器如何更改默认插槽中子组件的显示?它仅在不使用 CSS 的情况下处理显示/隐藏子组件。

应用程序.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>
javascript css vue.js vue-composition-api vuejs-slots
1个回答
0
投票

您可以通过向插槽的子级添加一个类来改变它们,使用嵌套选择器您可以隐藏插槽组件内的各个元素。

请注意,容器应该有一个像 DIV 这样的根 HTML 元素,以便

:deep()
正常工作。否则使用全局样式:

VUE SFC 游乐场

<script setup>

import { useSlots, reactive, cloneVNode} from 'vue';
const slots = useSlots();

const slotted = () => slots.default().map(vnode => cloneVNode(vnode, {class:{'hidden-child':hide.has(vnode.type.name)}}));


const hide = reactive(new Set);

function changeDisplay(whichChild) {
  hide.has(whichChild) ? hide.delete(whichChild) : hide.add(whichChild);
}

</script>

<template>
  <div>
  <button @click="changeDisplay('ChildA')">Toggle Child A</button>
  <button @click="changeDisplay('ChildB')">Toggle Child B</button>
  <slotted />
  </div>
</template>

<style scoped>
:deep(.hidden-child){
  display: none;
}
</style>
© www.soinside.com 2019 - 2024. All rights reserved.