Categories
Vue Answers

How to only show slot if it has content with Vue.js?

Spread the love

Sometimes, we want to only show slot if it has content with Vue.js.

In this article, we’ll look at how to only show slot if it has content with Vue.js.

How to only show slot if it has content with Vue.js?

To only show slot if it has content with Vue.js, we can check the this.$slots property in our component.

For instance, we write

<template>
  <div id="app">
    <div class="panel-footer" v-if="hasFooterSlot">
      <slot name="footer"></slot>
    </div>
  </div>
</template>

<script>
//...
export default {
  //...
  computed: {
    hasFooterSlot() {
      return !!this.$slots.footer;
    },
  },
  //...
};
</script>

to check if the footer slot is added with !!this.$slots.footer.

We put this in the hasFooterSlot computed property, so we can use that in our template with v-if to conditionally display the footer slot with

<div class="panel-footer" v-if="hasFooterSlot">
  <slot name="footer"></slot>
</div>

Conclusion

To only show slot if it has content with Vue.js, we can check the this.$slots property in our component.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *