When creating reusable component templates using slots, we typically define one or more slots within the component, allowing developers to insert custom content or components into these slots. This approach is widely applied across various frontend frameworks, such as Vue.js and React.
For example, in Vue.js, slots are a mechanism that enables parent components to insert content into child components. This not only enhances component flexibility but also ensures code clarity and maintainability.
Detailed Example
Suppose we want to create a reusable <Card> component with three sections: header, content, and footer. Each section's content should be customizable when using the component.
Card.vue:
vue<template> <div class="card"> <div class="card-header"> <slot name="header">Default header</slot> </div> <div class="card-body"> <slot>Default content</slot> </div> <div class="card-footer"> <slot name="footer">Default actions</slot> </div> </div> </template> <script> export default { name: 'Card' } </script> <style> .card { border: 1px solid #ccc; border-radius: 4px; padding: 20px; } .card-header, .card-footer { padding: 10px; background-color: #f7f7f7; } .card-body { padding: 10px; } </style>
In this component, we define three slots: header, the default slot (unnamed), and footer. Each slot provides default content to display when the user does not supply custom content.
Usage
vue<template> <Card> <template v-slot:header> <h1>This is the header</h1> </template> <p>This is some card content...</p> <template v-slot:footer> <button>Action button</button> </template> </Card> </template>
Here, we use the <template> tag and v-slot directive to specify content for each slot. The header and footer slots utilize named slots, while the main content uses the default slot.
Conclusion
By implementing this approach, the <Card> component becomes highly flexible, reusable across different pages and scenarios, and customizable each time it is used. This design not only improves code reusability but also ensures that each component section maintains strong customizability and independence.