Conditional Rendering in Named Slots
Illustrates how to conditionally render content within named slots based on certain data properties or computed values.
<style>
.content-container {
display: block;
border: 1px solid #ccc;
padding: 20px;
margin-top: 10px;
}
</style>
<template id="conditional-slot-template">
<div>
<slot name="header"></slot>
<slot name="main"></slot>
<!-- Only render this slot if footerVisible is true -->
<div class="content-container" v-if="footerVisible">
<slot name="footer"></slot>
</div>
</div>
</template>
Load this HTML segment which includes a template with named slots for 'header', 'main', and 'footer'. The 'footer' slot will be conditionally rendered based on a property named 'footerVisible'.
<div id="app">
<conditional-slot>
<template v-slot:header>
<h1>This is the header</h1>
</template>
<template v-slot:main>
<p>This is the main content</p>
</template>
<!-- This will render only if 'footerVisible' in the component state is true -->
<template v-slot:footer>
<p>This content appears in the footer</p>
</template>
</conditional-slot>
</div>
This HTML section uses the Vue components to define placeholders for the header, main, and footer. The 'footer' content will conditionally display based on 'footerVisible'.
Vue.component('conditional-slot', {
template: '#conditional-slot-template',
data() {
return {
footerVisible: false // Change this to true to show the footer slot
};
}
});
new Vue({
el: '#app'
});
This JavaScript defines a Vue component called 'conditional-slot' using the template from earlier. It has a 'data' property called 'footerVisible' that controls the visibility of the footer slot.