cssvue.jsvuejs3sfc

Is it possible to alter a named slot's css directly via data-attribute/name within vue?


after seeing this so-answer i got wondering if it is possible to address a named slot as described below (within vue):

<Parent
   <template #leading>
        ...
   </template>
</Parent>

<template>
  <div>
    <slot name="leading"></slot>
    <div>...</div>
  </div>
</template>
<style scoped>
:slotted([slot='leading']) {
    margin-right: 1rem;  
}
</style

Imagine a ListElement where you want to shift its children to the right only if the leading-slot actually exists.

Accessing the named slot like this would allow me to alter its content conditionally (if the slot is actually described or not) and would allow to me to implement a more data-driven approach.


Solution

  • simply use useSlots and apply css conditionally

    const slots = useSlots()
    
    const doesLeadingSlotExist = computed(() => {
        if ('leading' in slots) {
            return true;
        }
        return false;
    });
    

    Would have preferred a pure css solution but this approach also works.