Show only the display slot if it contains content

Is there a way to only show the slot if it has any content?

For example, I am creating a simple component Card.vue

and I only need a footer if the footer slot has content:

Template:

<template>
    <div class="panel" :class="panelType">
        <div class="panel-heading">
            <h3 class="panel-title">
                <slot name="title">
                    Default Title
                </slot>
            </h3>
        </div>
        <div class="panel-body">
            <slot name="body"></slot>
            <p class="category">
                <slot name="category"></slot>
            </p>
        </div>
        <div class="panel-footer" v-if="hasFooterSlot">
            <slot name="footer"></slot>
        </div>
    </div>
</template>

      

Script:

<script>
    export default {
        props: {
            active: true,
            type: {
                type: String,
                default: 'default',
            },
        },

        computed: {
            panelType() {
                return `panel-${this.type}`;
            },

            hasFooterSlot() {
                return this.$slots['footer']
            }
        }
    }
</script>

      

In view mode:

<card type="success"></card>

      

Since the above component does not contain a footer, it shouldn't be displayed, but it is.

I tried using this.$slots['footer']

but this returns undefined.

Does anyone have any tips?

+3


source to share


2 answers


It must be available

this.$slots.footer

      

So this should work.



hasFooterSlot() {
  return !!this.$slots.footer
}

      

An example .

+5


source


For this you need to check vm.$slots

as well vm.$scopedSlots

.



hasSlot (name = 'default') {
   return !!this.$slots[ name ] || !!this.$scopedSlots[ name ];
}

      

0


source







All Articles