Slots vs Props
#vue tips #coding tips #web dev
Updated January 4, 2024 | 1 min read
Slots in Vue.js give more flexibility than props, so when should we use which ?
In general, you should use slots to give the parent the freedom to customize components. On the other hand, you should use props if you have a defined design and need to change some values.
1- Props
Let's take a quick look at a simple Vue component that accepts a message as property:
<template>
<div>{{ msg }}</div>
</template>
<script>
export default {
name: 'HelloWorldProps',
props: {
msg: String,
},
};
</script>
<style scoped></style>
2- Slots
The following Vue component uses a slot instead of a property to show the message:
<template>
<div><slot /></div>
</template>
<script>
export default {
name: 'HelloWorldSlots',
props: {},
};
</script>
<style scoped></style>
3- Comparison
The following code shows how both components can be used in your Vue application:
<template>
<div>
<HelloWorldProps msg="Welcome to Your Vue.js App" />
<HelloWorldSlots>
<h2>Welcome to Your Vue.js App</h2>
</HelloWorldSlots>
</div>
</template>
As you can see, the slot provides more flexibility as you can pass any HTML code into the slot.