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.