Vue3实现tab切换

Vue3实现tab切换

使用 ref 创建了 tabscontentscurrentTab 这三个响应式变量,分别存储选项卡的文字、内容以及当前选中的选项卡索引。当点击某个选项卡时,调用 changeTab 函数来切换选项卡,并更新 currentTab 的值,从而更新选项卡的样式。

在样式中,我们定义了选项卡的样式,并且通过 v-show 来控制显示对应选项卡的内容。

最终效果就是点击不同的选项卡会切换到对应的内容,并且选中的选项卡文字带下划线,下划线宽度比文字宽度短,并且与文字居中。

js 复制代码
<template>
  <div>
    <div class="tab-container">
      <div
        v-for="(tab, index) in tabs"
        :key="index"
        @click="changeTab(index)"
        :class="{ 'selected': currentTab === index }"
        class="tab-item"
      >
        <span>{{ tab }}</span>
        <div v-if="currentTab === index" class="underline"></div>
      </div>
    </div>
    <div class="content-container">
      <div v-for="(content, index) in contents" :key="index" v-show="currentTab === index">
        {{ content }}
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';

const tabs = ref(['Tab 1', 'Tab 2', 'Tab 3']);
const contents = ref(['Content 1', 'Content 2', 'Content 3']);
const currentTab = ref(0);

const changeTab = (index: number) => {
  currentTab.value = index;
};
</script>

<style scoped>
.tab-container {
  display: flex;
}

.tab-item {
  cursor: pointer;
  margin-right: 20px;
  position: relative;
}

.underline {
  position: absolute;
  bottom: 0;
  left: 50%;
  width: 50%; /* 下划线宽度比文字宽度短 */
  height: 2px;
  background-color: blue;
  transform: translateX(-50%);
}

.selected {
  font-weight: bold;
}

.content-container {
  margin-top: 20px;
}
</style>
相关推荐
杨先生哦6 小时前
2026 热端攻防:AI 驱动 Web 前端安全全景透析
前端·笔记·安全·web安全
李白的天不白6 小时前
SmartAdmin(基于 Spring Boot 框架)中配置跨域请求 VUE3 设置请求头
java·前端
一个被程序员耽误的厨师6 小时前
01-设计篇-我用前端那一套手艺造了一个AI-Native工具
前端·ai-native
不吃糖葫芦37 小时前
vue3实现拓扑图编辑功能(谨以此纪念我当前的最后一份前端工作)
前端
大家的林语冰7 小时前
超越 TypeScript,Flow 强势回归,语法高仿 TS,功能更丰富,类型更安全!
前端·javascript·typescript
星空7 小时前
html\css\js入门
javascript·css·html
重生之我是Java开发战士7 小时前
【Java SE】多线程(三):单例模式,阻塞队列,线程池与定时器
java·javascript·单例模式
lijgvnns7 小时前
个人AI编程工具的vibe coding实践:从爬虫到导出Excel的全流程
开发语言·javascript·ecmascript
এ慕ོ冬℘゜7 小时前
jQuery 高可用多图上传组件(企业级封装 + 踩坑全解 + 可直接上线)
前端·javascript·jquery