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?
To only show slot if it has content with Vue. js, we can check the this. $slots property in our component. to check if the footer slot is added with !!
With Vue slots, you can turn a part or all of your components into reusable templates that will render differently based on different use cases. All you need to do is embed them in slots.
It should be available at
this.$slots.footer
So, this should work.
hasFooterSlot() { return !!this.$slots.footer }
Example.
You should check vm.$slots
and also vm.$scopedSlots
for it.
hasSlot (name = 'default') { return !!this.$slots[ name ] || !!this.$scopedSlots[ name ]; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With