vue3 tab
时间: 2025-06-01 18:21:29 浏览: 17
### Vue3 中 Tab 组件的实现与使用
在 Vue 3 中,Tab 组件可以通过组合式 API 和模板语法来实现。以下是一个基于 Vue 3 的 Tab 组件的实现示例[^2]。
#### 基本实现逻辑
Tab 组件通常包含两个主要部分:`Tabs` 和 `TabPane`。`Tabs` 是父组件,用于管理所有标签页的状态和切换逻辑;`TabPane` 是子组件,表示每个具体的标签页内容。
#### 实现代码示例
```vue
<template>
<div class="tabs">
<ul class="tab-header">
<li
v-for="(tab, index) in tabs"
:key="index"
:class="{ active: activeIndex === index }"
@click="setActiveTab(index)"
>
{{ tab.title }}
</li>
</ul>
<div class="tab-content">
<slot></slot>
</div>
</div>
</template>
<script setup>
import { ref, provide, watchEffect } from 'vue'
const props = defineProps({
modelValue: {
type: Number,
default: 0
}
})
const activeIndex = ref(props.modelValue)
const tabs = []
const setActiveTab = (index) => {
activeIndex.value = index
}
provide('activeIndex', activeIndex)
provide('addTab', (tab) => tabs.push(tab))
watchEffect(() => {
if (!tabs[activeIndex.value]) {
activeIndex.value = 0
}
})
</script>
<style scoped>
.tabs {
width: 100%;
}
.tab-header {
list-style: none;
padding: 0;
margin: 0;
display: flex;
}
.tab-header li {
padding: 10px;
cursor: pointer;
background-color: #f4f4f4;
border: 1px solid #ccc;
margin-right: -1px;
}
.tab-header li.active {
background-color: #fff;
font-weight: bold;
}
.tab-content {
padding: 10px;
border: 1px solid #ccc;
border-top: none;
}
</style>
```
#### 子组件 TabPane 实现
```vue
<template>
<div v-if="isActive">
<slot></slot>
</div>
</template>
<script setup>
import { inject, reactive } from 'vue'
const activeIndex = inject('activeIndex')
const addTab = inject('addTab')
const props = defineProps({
title: {
type: String,
required: true
}
})
const state = reactive({
isActive: false,
index: null
})
addTab({
title: props.title,
isActive: () => state.isActive
})
watchEffect(() => {
state.isActive = activeIndex.value === state.index
})
</script>
```
#### 使用示例
```vue
<template>
<Tabs v-model:modelValue="selectedTab">
<TabPane title="Home">Home Content</TabPane>
<TabPane title="Profile">Profile Content</TabPane>
<TabPane title="Settings">Settings Content</TabPane>
</Tabs>
</template>
<script setup>
import { ref } from 'vue'
import Tabs from './Tabs.vue'
import TabPane from './TabPane.vue'
const selectedTab = ref(0)
</script>
```
### 相关说明
上述实现中,`Tabs` 父组件通过 `provide` 和 `inject` 提供了状态共享机制,子组件 `TabPane` 可以通过注入的方式获取当前激活的索引并判断自身是否需要渲染[^2]。
此外,VueStrap 提供了一套基于 Bootstrap 的 Vue.js 组件库,其中也包含了 Tab 组件的封装[^3]。如果需要快速集成 Tab 功能,可以直接使用此类第三方库。
阅读全文
相关推荐
















