Vue3实现tab切换

Vue3实现tab切换

使用 ref 创建了 tabs、contents 和 currentTab 这三个响应式变量,分别存储选项卡的文字、内容以及当前选中的选项卡索引。当点击某个选项卡时,调用 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>
相关推荐
看浪的路人几秒前
第9讲:大模型应用监控与可观测性——OpenTelemetry + Prometheus + Grafana 全链路追踪
java·前端·spring
内存过载1 分钟前
用表格模拟甘特图:项目排期的土办法
前端·低代码
葡萄城技术团队10 分钟前
用 SpreadJS 数据验证实现省市区三级联动
前端
派小心.33 分钟前
A/B实验分层随机种子的稳定性验证
大数据·服务器·前端·数据分析
袋鼠云数栈UED团队42 分钟前
从 Skills 到可靠的 Bugfix Agent
前端
幼儿园蛋小黑1 小时前
SPI 子系统:从原理到实践
java·前端·数据库
雪雪爱冲浪1 小时前
JavaScript 网络爬虫教程(2026)
开发语言·javascript·爬虫
Data analyse4561 小时前
rrweb回放事件资源加载顺序重放校验
前端·人工智能·算法·机器学习·数据分析
软件技术NINI1 小时前
化妆品html+css+js 7页
javascript·css·html
要吃这碗饭1 小时前
JavaScript 网络爬虫教程(2026)
开发语言·javascript·爬虫