Vue Slot Example
You can add a slot element to the template of a component. The slot acts as a placeholder for when you use the component. When you use the component, you can put things inside the opening and closing tags (things like HTML elements or Vue components). For example, if you have a component named MyComponent that has a slot in it, you might use this component like so:
<my-component>
<p>This paragraph will get placed inside the SLOT element in MyComponent</p>
</my-component>
The p element will get placed inside MyComponent's slot.
Let's create a working example!
Create a file named ComponentWithSlot.vue in the components folder. Then put this code in it:
<template>
<h1>This component has a SLOT in it!</h1>
<p>I put a DIV with a border around the slot so you can see it.</p>
<div class="add-border">
<slot></slot>
</div>
</template>
<style scoped>
.add-border{
border:2px solid red;
}
</style>
Note that there is a slot element in the template.
Now we'll create a component that makes use of ComponentWithSlot. Create a file in the views folder named SlotExample.vue and put this code in it:
<template>
<component-with-slot>
<hello-world />
<h3>I also added this to the slot</h3>
</component-with-slot>
</template>
<script>
import ComponentWithSlot from '@/components/ComponentWithSlot.vue';
import HelloWorld from '@/components/HelloWorld.vue';
export default {
components:{ComponentWithSlot, HelloWorld}
}
</script>
Notice the component-with-slot element in the template, it has two elements nested inside of it. These two elements will get placed inside the slot.
If you are adding this example to your Vue Playground project, you should set up a route that leads to the SlotExample component, and add a router-link to App.vue that allows you to navigate to it.
Slots in Vue allow you to create components that can change when you use them in different parts of your app. For example, you could use ComponentWithSlot in another part of your app and put different elements in the slot.