본문 바로가기
Web/JavaScript

[Vue3] Slot (v-slot) Usage

by llHoYall 2021. 6. 20.

We can define the common framework of the template using slot to make the code neatly.

Create a Project

Let's create a project first.

2021.06.02 - [Web/JavaScript] - [Vue3] Getting Started with Vue3 + TypeScript + TailwindCSS

Create a Common Layout

Now, let's define the common layout.

 

components/slot_layout.vue

<template>
  <div class="p-4 flex flex-col justify-center items-center">
    <header class="text-2xl font-medium text-green-400">
      <slot name="header"></slot>
    </header>
    <main class="mt-8 text-xl font-medium text-green-600">
      <slot></slot>
    </main>
    <footer class="mt-8 text-md font-medium text-green-800">
      <slot name="footer"></slot>
    </footer>
  </div>
</template>

I created three slots and gave them a name.

The unnamed slot has default as the default name.

i.e., <slot> is the same as <slot name="default">.

Use a Common Layout

Now, let's make a component with the common layout.

 

components/use_slot.vue

<template>
  <SlotLayout>
    <template v-slot:header>
      <div>Header</div>
    </template>
    <template v-slot:default>
      <div>Body</div>
    </template>
    <template #footer>
      <div>Footer</div>
    </template>
  </SlotLayout>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import SlotLayout from "./slot_layout.vue";

export default defineComponent({
  name: "UseSlot",
  components: { SlotLayout },
});
</script>

We can set the data to the slot using template and v-slot. # is a short notation of v-slot.

Rendering It

It's the time to test this.

 

App.vue

<template>
  ><UseSlot />
</template>

<script lang="ts">
import { defineComponent } from "vue";
import UseSlot from "./components/use_slot.vue";

export default defineComponent({
  name: "App",
  components: { UseSlot },
});
</script>

It works well.

Conclusion

Now, we know how to create a common layout for similar components.

We can effectively reduce the repeated code.

Apply this to your project now!

'Web > JavaScript' 카테고리의 다른 글

[Vue3] Custom Directives  (0) 2021.06.24
[Vue3] Send Data from Ancestor Component using Provide and Inject  (0) 2021.06.20
[Vue3] Component Usage  (0) 2021.06.20
[Vue3] Vue-Router Usage  (0) 2021.06.18
[Vue3] Lifecycle  (0) 2021.06.16

댓글