I'm trying to set up a component with a slot, that when rendered adds a class to every children of that slot. In a very simplified manner:
<template>
<div>
<slot name="footerItems"></slot>
</div>
</template>
How would I go about this? My current solution is to add the class to the elements in 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, the elements lose the styling whenever it's rerendered (using npm run serve) and also jest tests give me 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 move the slot to its own component and use a render function there? But even then I'm not sure how to edit the children to add the classes or how to produce several root level elements from the render function.