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>
相关推荐
excel10 分钟前
JS 正则在多次 test() 时为什么会出现 lastIndex 缓存问题?
前端
IT_陈寒12 分钟前
为什么 Java 的 Optional 让我调试到深夜?
前端·人工智能·后端
米丘42 分钟前
React 19.x 的 lazy 与 Suspense
前端·javascript·react.js
如果超人不会飞1 小时前
TinyVue Grid 表格 fetchData 完全指南:从入门到精通
前端
kyriewen1 小时前
手写虚拟DOM后,我反问面试官:key为什么不能用index?
前端·react.js·面试
Doris_20231 小时前
说一说ESLint+Prettier生效的原理
前端·设计模式·架构
ZC跨境爬虫1 小时前
跟着 MDN 学CSS day_21:(图像溢出控制与表单元素样式定制)
前端·javascript·css·ui·交互
卷帘依旧2 小时前
微前端解决方案-qiankun
前端
moshuying2 小时前
你做的,比汇报出来的多得多
前端
shuye2162 小时前
google chrome 离线下载地址
前端·chrome