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>
相关推荐
白狐_79832 分钟前
408数据结构:中缀转后缀与操作符栈容量——真题精讲
前端·javascript·数据结构
谷哥的小弟34 分钟前
TypeScript在Vue3中的常见写法
前端·javascript·typescript
人间凡尔赛1 小时前
2026 前端全栈新范式:Server Actions + Edge Runtime,告别传统 API 路由
前端·全栈·next.js
mONESY2 小时前
用 useRef 管理 Worker 线程,让你的页面不再卡顿
javascript
码林鼠4 小时前
2026前端面试题(二)
前端
满栀5855 小时前
请求拦截、响应拦截、业务错误统一处理
前端·typescript·anti-design-vue
vx-程序开发6 小时前
django医院预约挂号系统---附源码23353
java·javascript·spring boot·python·eclipse·django·php
宿6746 小时前
tsconfig.node.json
前端·javascript·vue.js
小杨互联网6 小时前
Cursor 前端 Dist 自动化逆向框架:/fr 流水线 · 4 脚本 · Vite/Webpack
前端·webpack·自动化·前端逆向框架·ai前端逆向框架
瑞码空间6 小时前
Web应用的多端部署之道:浏览器 · Electron · Docker
前端·docker·electron·浏览器·web