Optimize your Vue.js components - Learn when props are best suited and when slots are a better choice. Find out more now!
19. September 2024
In Vue.js, props and slots serve unique purposes and offer different advantages based on the use case.
Props allow data to be passed from a parent component to a child component, which is useful when the child component requires specific and predictable data.
Slots enable dynamic content exchange between components, providing more flexibility as the content can be defined at runtime.
Props are ideal when a component needs specific data that should not be changed during runtime.
<template>
<button :style="{ color: textColor }">
<span v-if="icon">{{ icon }}</span>
{{ text }}
</button>
</template>
<script lang="ts" setup>
import { defineProps } from 'vue'
const props = defineProps({
text: String,
icon: String,
textColor: String,
})
</script>
<template>
<CustomButtonWithProps text="Click Me" icon="👍" textColor="blue" />
</template>
<script lang="ts" setup>
import CustomButtonWithProps from './CustomButtonWithProps.vue'
</script>
Props are useful when a component's structure and behavior are clearly defined and unchanging.
Slots are beneficial when a component needs to contain content that can be flexibly changed at runtime.
<template>
<button>
<slot name="icon"></slot>
<slot></slot>
</button>
</template>
<script lang="ts" setup>
</script>
<template>
<CustomButtonWithSlots>
<template #icon>
<span>👍</span>
</template>
Click Me
</CustomButtonWithSlots>
</template>
<script lang="ts" setup>
import CustomButtonWithSlots from './CustomButtonWithSlots.vue'
</script>
Slots make components more reusable and flexible as they are not constrained by predefined content.
Example components that use simple and predictable data.
<template>
<div class="card">
<h1>{{ title }}</h1>
<p>{{ description }}</p>
</div>
</template>
<script lang="ts" setup>
import { defineProps } from 'vue'
const props = defineProps({
title: String,
description: String,
})
</script>
Components that can contain various types of content.
<template>
<div class="card">
<slot name="header"></slot>
<slot></slot>
<slot name="footer"></slot>
</div>
</template>
<script lang="ts" setup>
</script>
Choosing between props and slots depends on the specific use case.
Often, a combination of both is the optimal approach.
<template>
<div>
<slot name="header" :title="title"></slot>
<slot></slot>
<slot name="footer"></slot>
</div>
</template>
<script lang="ts" setup>
import { defineProps } from 'vue'
const props = defineProps({
title: String,
})
</script>
Props and slots each have their respective advantages and use cases. Props are ideal for static content and clear data transfers, while slots are better for dynamic content and increased flexibility.