Using Slots in Vue 2 (Options API)

 ← Dev Articles
👍 0
👎 0

Slots in Vue let you create reusable components where the parent controls part of the content. 

 

1. Create a reusable component (Card.vue)

 

 <template>

   <div class="card">

     <div class="card-header">

       <!-- Named slot for header -->

       <slot name="header">Default Header</slot>

     </div>

 

     <div class="card-body">

       <!-- Default slot -->

       <slot>Default content goes here...</slot>

     </div>

 

     <div class="card-footer">

       <!-- Named slot for footer -->

       <slot name="footer">Default Footer</slot>

     </div>

   </div>

 </template>

 

 <script>

 export default {

   name: "Card"

 }

 </script>

 

 

2. Use the component in a parent (App.vue or a Blade-Vue view)

 

 <template>

   <div>

     <h1>Vue 2 Slots Example</h1>

 

     <Card>

       <template v-slot:header>

         Custom Header: Article Info

       </template>

 

       This is the article body content coming from the parent.

 

       <template v-slot:footer>

         <button @click="sayHello">Click Me</button>

       </template>

     </Card>

 

     <!-- Another card with defaults -->

     <Card />

   </div>

 </template>

 <script>

 import Card from "./Card.vue";

 export default {

   name: "App",

   components: { Card },

   methods: {

     sayHello() {

       alert("Hello from slot footer button!");

     }

   }

 }

 </script>