I am currently in the process of setting up a component with a slot that, upon rendering, adds a specific class to each child within that slot. To simplify:
<template>
<div>
<slot name="footerItems"></slot>
</div>
</template>
How can I achieve this? My current approach involves adding the class to elements using an onBeforeUpdate
hook:
<script setup lang="ts">
import { useSlots, onMounted, onBeforeUpdate } from 'vue';
onBeforeUpdate(() => addClassToFooterItems());
onMounted(() => addClassToFooterItems());
function addClassToFooterItems() {
const slots = useSlots();
if (slots && slots.footerItems) {
for (const item of slots.footerItems()) {
item.el?.classList.add("card-footer-item");
}
}
}
</script>
However, when rerendered (using npm run serve
), the elements lose their styling. Additionally, Jest tests yield a warning:
[Vue warn]: Slot "footerItems" invoked outside of the render function: this will not track dependencies used in the slot. Invoke the slot function inside the render function instead.
Should I consider moving the slot to its own component and utilizing a render function there? Even then, I am unsure how to manipulate children to add classes or generate multiple root-level elements through the render function.