vue.jsvuejs2

Only show slot if it has content


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

For example, I'm building a simple Card.vue component, and I only want the footer displayed 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 in View:

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

Since the above component doesn't contain a footer, it should not be rendered, but it is.

I've tried using this.$slots['footer'], but this returns undefined.

Does anyone have any tips?


Solution

  • It should be available at

    this.$slots.footer
    

    So, this should work.

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

    Example.