Javascript is required
·
1 min read
·
1505 views

Vue Tip: Prefer Slots Over Props

Vue Tip: Prefer Slots Over Props Image

Slots in Vue.js give more flexibility than props.

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.

Let's take a quick look at a simple Vue component that accepts a message as property:

1<template>
2  <div>{{ msg }}</div>
3</template>
4
5<script>
6export default {
7  name: 'HelloWorldProps',
8  props: {
9    msg: String,
10  },
11}
12</script>
13
14<style scoped></style>

The following Vue component uses a slot instead of a property to show the message:

1<template>
2  <div><slot /></div>
3</template>
4
5<script>
6export default {
7  name: 'HelloWorldSlots',
8  props: {},
9}
10</script>
11
12<style scoped></style>

The following code shows how both components can be used in your Vue application:

1<template>
2  <div>
3    <HelloWorldProps msg="Welcome to Your Vue.js App" />
4    <HelloWorldSlots>
5      <h2>Welcome to Your Vue.js App</h2>
6    </HelloWorldSlots>
7  </div>
8</template>

As you can see, the slot provides more flexibility as you can pass any HTML code into the slot.

If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:

I will never share any of your personal data. You can unsubscribe at any time.