Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only show slot if it has content

Tags:

vue.js

vuejs2

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?

like image 904
Steve Bauman Avatar asked May 19 '17 19:05

Steve Bauman


People also ask

How do I know if my Vue slot has content?

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 !!

What is a Vue slot?

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.


2 Answers

It should be available at

this.$slots.footer 

So, this should work.

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

Example.

like image 92
Bert Avatar answered Sep 18 '22 05:09

Bert


You should check vm.$slots and also vm.$scopedSlots for it.

hasSlot (name = 'default') {    return !!this.$slots[ name ] || !!this.$scopedSlots[ name ]; } 
like image 37
Madmadi Avatar answered Sep 22 '22 05:09

Madmadi