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>
相关推荐
喵个咪34 分钟前
GoWind 拆解:全链 ID 类型体系——int64 定版与前端字符串化契约
前端·后端·go
喵个咪39 分钟前
GoWind CMS 拆解:Flutter 设计系统内核——双态 token、四档断点与自适应壳层
前端·flutter·交互设计
喵个咪1 小时前
GoWind CMS 拆解:发布审批——多级推进、逐级角色与全程留痕
前端·后端·go
喵个咪1 小时前
GoWind Flow 拆解:一个 Go 工作流引擎与它的双模式设计器
前端·后端·go
喵个咪2 小时前
GoWind Admin 拆解:打印模板设计器——从画布到服务端 PDF 的完整打印链路
前端·后端·go
总要学点什么2 小时前
第96篇:三维数据加载-城市建筑白模样式+着色器——让色带按体量上色,最白的那档却涂不上去
前端·gis·webgl·cesium·着色器·空间分析·白模
Hilaku2 小时前
你们公司有 35 岁以上的前端吗?
前端·javascript·程序员
徐小夕3 小时前
开源Vector-Graph-RAG:向量+图谱双引擎,打破纯向量RAG的效果天花板
前端·vue.js·github
SameX3 小时前
HarmonyOS ArkTS 把组件截图保存成 PNG 再调系统分享面板的做法
前端
Swot3 小时前
SvelteKit SSG 发布后,为什么老访客非要强刷才能看到新内容?
前端