Slot vs Props in Vue: Key Differences and Usage Guide
props are used to pass data from a parent component to a child component as variables, while slots allow passing template content or HTML from parent to child for flexible layout. Props handle data values, and slots handle content structure.Quick Comparison
Here is a quick side-by-side comparison of props and slots in Vue:
| Aspect | Props | Slots |
|---|---|---|
| Purpose | Pass data values to child | Pass template content to child |
| Type of data | Variables like strings, numbers, objects | HTML or Vue templates |
| Usage | Child accesses data via props | Child renders passed content inside <slot> |
| Flexibility | Fixed data structure | Flexible content and layout |
| Example | <Child :title="parentTitle" /> | <Child><template #header>Custom</template></Child> |
Key Differences
Props are designed to send data from a parent component to a child component in a structured way. They are like function arguments that the child expects to receive and use internally. Props are reactive, so if the parent changes the value, the child updates automatically.
Slots, on the other hand, let the parent pass chunks of HTML or Vue templates to the child. This allows the child to render flexible content inside its layout. Slots are useful when the child component needs to display different content depending on the parent’s needs.
While props focus on passing data, slots focus on passing content structure. You can think of props as passing ingredients to a recipe, and slots as passing a ready-made dish to be served inside a container.
Code Comparison
<!-- ParentComponent.vue --> <template> <ChildComponent :message="parentMessage" /> </template> <script setup> import ChildComponent from './ChildComponent.vue' import { ref } from 'vue' const parentMessage = ref('Hello from parent') </script> <!-- ChildComponent.vue --> <template> <p>{{ message }}</p> </template> <script setup> const props = defineProps({ message: String }) </script>
Slots Equivalent
<!-- ParentComponent.vue -->
<template>
<ChildComponent>
<template #default>
<p>Hello from parent slot content</p>
</template>
</ChildComponent>
</template>
<script setup>
import ChildComponent from './ChildComponent.vue'
</script>
<!-- ChildComponent.vue -->
<template>
<div>
<slot />
</div>
</template>
<script setup>
// No props needed here
</script>When to Use Which
Choose props when you want to pass specific data values that the child component needs to function or display. Props are best for fixed data inputs and keep components predictable.
Choose slots when you want to pass flexible content or HTML structure that the child should render inside its layout. Slots are ideal for customizing parts of a component’s UI without changing its logic.
In many cases, you will use both together: props for data and slots for content layout.