Javascript is required
Mokkapps Logo

Vue Tip: Prefer Slots Over Props

Michael Hoffmann (Mokkapps) - Senior Frontend Developer (Freelancer)
Nov 10, 2021
1 min read
|
73 views
Template
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:

<template>  <div>{{ msg }}</div></template><script>export default {  name: 'HelloWorldProps',  props: {    msg: String,  },}</script><style scoped></style>

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>

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.


If you liked this Vue tip, follow me on Twitter to get notified about new tips, blog posts, and more content from me. Alternatively (or additionally), you can also subscribe to my newsletter.