DEV Community

Ahmet Meliksah Akdeniz
Ahmet Meliksah Akdeniz

Posted on • Edited on

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)

Top comments (0)