The Difference Between Props, Slots and Scoped Slots in Vue.js

Let’s see what is the best way to pass data between components

Luca Spezzano
NotOnlyCSS
Published in
4 min readOct 26, 2020

--

Puzzle
Photo by Bianca Ackermann on Unsplash

When I started using Vue, I just passed data between components through the props, deepening this framework I found that I could achieve the same result with slots.

Let’s understand the differences and the reasons for using props instead of slots and vice versa.

PROPS

They are attributes that are exposed to accept data from the parent component.

Let’s create a component MyMessage with props

<template>
<div class="message">
<h1>{{ msg }}</h1>
</div>
</template>
<script>
export default {
name: "MyMessage",
props: {
msg: String,
},
};
</script>
<style scoped>
.message {
color: red;
text-decoration: underline;
}
</style>

In this way, we are saying that the component accepts a value called msg.

Now when we use this component we are able to pass a value through an attribute

<template>
<my-message msg="NotOnlyCSS is awesome!" />
</template>
<script>
import MyMessage from "./components/MyMessage.vue";
export default {
name: "App",
components: {
MyMessage,
},
};
</script>

You can see the demo and play with props here on codesandbox.

Well I think it is now clear how the props work.

SLOTS

They allow you to compose component, also with HTML code.

Let’s create a component MyMessage with slots

<template>
<div class="message">
<slot />
</div>
</template>
<script>
export default {
name: "MyMessage",
};
</script>
<style scoped>
.message {
color: red;
text-decoration: underline;
}
</style>

--

--

Luca Spezzano
NotOnlyCSS

Frontend developer focused on CSS architecture of scalable and maintainable large scale projects and the development of amazing user interfaces.

Recommended from Medium

Lists

See more recommendations