在 Vue3 中设置选项卡可以通过以下步骤实现,这里使用组合式 API(Composition API)和 <script setup>
语法:
1. 创建选项卡组件
<template>
<div class="tabs-container">
<!-- 选项卡标签头 -->
<div class="tabs-header">
<button
v-for="(tab, index) in tabs"
:key="index"
@click="activateTab(index)"
:class="{ 'active-tab': activeTab === index }"
>
{{ tab.title }}
</button>
</div>
<!-- 选项卡内容区域 -->
<div class="tabs-content">
<div
v-for="(tab, index) in tabs"
:key="index"
v-show="activeTab === index"
>
{{ tab.content }}
</div>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue';
// 定义选项卡数据
const tabs = ref([
{ title: '标签1', content: '这里是第一个标签的内容' },
{ title: '标签2', content: '这里是第二个标签的内容' },
{ title: '标签3', content: '这里是第三个标签的内容' },
]);
// 当前激活的标签索引
const activeTab = ref(0);
// 切换标签方法
const activateTab = (index) => {
activeTab.value = index;
};
</script>
<style scoped>
.tabs-container {
width: 500px;
margin: 20px auto;
}
.tabs-header {
display: flex;
border-bottom: 2px solid #eee;
}
.tabs-header button {
padding: 10px 20px;
background: none;
border: none;
cursor: pointer;
font-size: 16px;
transition: all 0.3s;
}
.tabs-header button:hover {
color: #42b983;
}
.active-tab {
color: #42b983;
border-bottom: 2px solid #42b983 !important;
}
.tabs-content {
padding: 20px;
min-height: 150px;
}
</style>
2. 代码说明
-
响应式数据:
tabs
:使用ref
存储选项卡数据,每个选项卡包含标题(title)和内容(content)activeTab
:记录当前激活的选项卡索引
-
模板部分:
- 使用
v-for
循环渲染标签按钮 - 通过
@click
事件切换激活状态 v-show
根据激活状态显示/隐藏内容
- 使用
-
样式设计:
- 通过
.active-tab
类高亮当前选中的标签 - 添加悬停效果提升交互体验
- 通过
3. 进阶用法
使用动态组件(适合复杂内容)
<script setup>
import { ref, defineAsyncComponent } from 'vue';
// 动态导入组件
const components = [
defineAsyncComponent(() => import('./Tab1.vue')),
defineAsyncComponent(() => import('./Tab2.vue')),
defineAsyncComponent(() => import('./Tab3.vue'))
];
const activeTab = ref(0);
</script>
<template>
<component :is="components[activeTab]" />
</template>
添加过渡动画
<template>
<transition name="fade" mode="out-in">
<div :key="activeTab">
<!-- 内容区域 -->
</div>
</transition>
</template>
<style>
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
</style>
4. 使用注意事项
- 可访问性:可以添加
role="tablist"
等 ARIA 属性 - 响应式设计:使用媒体查询优化移动端显示
- 性能优化:内容较多时建议使用
v-show
替代v-if
最终效果:创建了一个包含三个标签的可切换界面,点击标签头会显示对应的内容区域,并伴有样式变化提示当前激活状态。