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>
相关推荐
meilindehuzi_a1 小时前
Vue3组件样式隔离与组件通信实战:从 scoped、props 校验到记事本应用
前端·javascript·vue.js
LaughingZhu1 小时前
Product Hunt 每日热榜 | 2026-07-28
前端·神经网络·react.js·搜索引擎·前端框架
陈随易8 小时前
在 VSCode 里,把项目一键部署到服务器
前端·后端·程序员
Highcharts.js8 小时前
教程:基于 React + Highcharts 构建一个单页应用程序、按需数据拉取与图表渲染
开发语言·前端·数据结构·react.js·前端框架·highcharts·页面应用
To_OC9 小时前
我被 useState 坑了两次之后,终于把它的脾气摸透了
前端·javascript·react.js
鱼樱前端9 小时前
我用 Claude Code 后,编码效率翻 3 倍。但更值钱的是别的。
前端·后端·ai编程
_lucas9 小时前
给知识库网站接入AI问答
前端·ai编程·全栈
前端糕手10 小时前
前端面试题大全:JavaScript + Vue3 + React + TypeScript + 工程化 + 性能优化
前端
我不叫武11 小时前
一个用 Rust 写的离线编码查询桌面工具
前端
Web4Browser12 小时前
指纹浏览器 API 自动化怎么接:启动 Profile、获取 CDP 端点并连接自动化框架
前端·网络·typescript·自动化