---
# System prepended metadata

title: Nuxt3 使用 slots 製作 Tab
tags: [Nuxt3.js]

---

# Nuxt3 使用 slots 製作 Tab

`TabWrapper.vue`:

```htmlembedded
<template>
  <div class="tab">
    <ul class="d-flex list-unstyled gap-1">
      <li v-for="item in titles" :key="item">
        <a class="d-block px-3 py-1 border" @click.prevent="selectedTitle = item" href="#">{{ item }}</a>
      </li>
    </ul>
    <slot />
  </div>
</template>

<script setup lang="ts">
const slots = defineSlots()
const titles = ref(slots.default().map((t: { props: { title: string; }; }) => t.props.title))
const selectedTitle = ref(titles.value[0])
provide('selectedTitle', selectedTitle)
</script>
```

`Tab.vue`:

```htmlembedded
<template>
  <div class="tab-content" v-show="props.title == selectedTitle">
    <slot />
  </div>
</template>

<script setup>
const props = defineProps(['title'])
const selectedTitle = inject('selectedTitle')
</script>
```

`app.vue`:
```htmlembedded
<TabWrapper>
  <Tab title="tab1">111 Lorem ipsum dolor sit amet.</Tab>
  <Tab title="tab2">222 Lorem ipsum dolor sit amet.</Tab>
  <Tab title="tab3">333 Lorem ipsum dolor sit amet.</Tab>
  <Tab title="tab4">444 Lorem ipsum dolor sit amet.</Tab>
</TabWrapper>
```