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>
相关推荐
Csvn12 分钟前
Vue Router 实战
前端·vue.js
yqcoder14 分钟前
JavaScript 内存揭秘:堆(Heap) vs 栈(Stack)
开发语言·javascript·ecmascript
IT_陈寒36 分钟前
JavaScript实战技巧总结
前端·人工智能·后端
玲小珑39 分钟前
AI Coding 与 Harness 实践精髓:让AI高效干活、持续交付
前端·人工智能·openai
skilllite作者41 分钟前
Agent-Skills 核心能力与实战效能深度评测
大数据·开发语言·前端·数据库·人工智能·python
恋猫de小郭43 分钟前
实用性 Max ,新 Flutter & Dart Agent Skills 深度解读
android·前端·flutter
一诺加油鸭1 小时前
若依(RuoYi)框架中普通用户角色登录后访问接口报 403 “当前操作没有权限”错误的完整解决方案
前端
宁雨桥1 小时前
AI前端开发面试题分享
前端·人工智能·ai
亿元程序员1 小时前
求求你别卷了,主管又转发你的文章到工作群了...我看了之后五味杂陈,决定卷个毛线!
前端
kyriewen111 小时前
你的前端滤镜慢得像PPT?用Rust+WebAssembly,一秒处理4K图
开发语言·前端·javascript·设计模式·rust·ecmascript·powerpoint