DEV Community

Ahmet Meliksah Akdeniz
Ahmet Meliksah Akdeniz

Posted on • Edited on

1

Vue.js Basics Part 9 | Slots

Today, I will be talking about slots in Vue.js.

This is part 9 of my Vue.js Basics series, to read part 8, please click here (spoiler! Part 8 is about emit)

Parent components have another way of passing data to child components; via slots:

<script>
import ChildComp from './ChildComp.vue'

export default {
  components: {
    ChildComp
  },
  data() {
    return {
      msg: 'from parent'
    }
  }
}
</script>

<template>
  <ChildComp> {{msg}} </ChildComp>
</template>
Enter fullscreen mode Exit fullscreen mode

That {{msg}} there, is a slot. First, let me talk about the code line by line. import ChildComp from './ChildComp.vue' import child component. Register it in components option like so:

components: {
    ChildComp
  },
Enter fullscreen mode Exit fullscreen mode

Last part of our script tag is data which holds only a data of string type msg: 'from parent'. After that we've got
<ChildComp> {{msg}} </ChildComp>. Remember when we use components in Vue, we only used them like this <ChildComp />. However, here we put something in between them like so; <ChildComp> {{msg}} </ChildComp>. So, whatever gets in between component tags are slots. Hence, syntax is this <ComponentName> I AM A SLOT :) </ComponentName>

Here's our child component:

<template>
  <slot />
</template>
Enter fullscreen mode Exit fullscreen mode

All we need to do to use slots is just using <slot /> tag. If you you want a fallback in case there's no slot from parent, then you can do it like so; <slot> I'am a fallback :) </slot>.

Today I've talked about slots in Vue which is another way to send content from parent to child component. By doing this I finished the Vue tutorial.

Next, I'm planning to do a portfolio website (it's only one-page)

AWS Q Developer image

Your AI Code Assistant

Implement features, document your code, or refactor your projects.
Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay