vue 中如何实现 tab 切换功能?

凸显选中的小栗子

最下方有完整代码cv走可以进行调试。

html部分解释

  • Tab 按钮: 使用 v-for 遍历 tabs 数组中的每个对象,生成相应数量的 tab 按钮。通过 :class 动态绑定类名,当 currentIndex 等于当前循环的索引时,添加 active 类,以突显当前选中的 tab。

  • 显示当前选中的 Tab 内容: 使用 v-show 根据 currentIndex 的值来条件性地显示当前选中的 tab 内容。

js部分解释

  • 数据部分(data):data 函数中定义了组件的初始状态,包括 tabs 数组和 currentIndextabs 数组中包含了每个 tab 的名称和内容,而 currentIndex 表示当前选中的 tab 的索引。

  • 方法部分(methods): 提供了 changeTab 方法,当 tab 被点击时触发,用于更新 currentIndex,从而切换到相应的 tab。

cs部分解释

通过添加样式,突显了选中的 tab。.active 类被定义为加粗文字、蓝色文本、并改变鼠标指针形状,以提高交互性。

完整代码
<template>
  <div>
    <!-- Tab 按钮 -->
    <div
      v-for="(tab, index) in tabs"
      :key="index"
      @click="changeTab(index)"
      :class="{ active: currentIndex === index }"
    >
      {{ tab.name }}
    </div>

    <!-- 显示当前选中的 Tab 内容 -->
    <div v-show="currentIndex === selectedTab">
      {{ tabs[currentIndex].content }}
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tabs: [
        { name: 'Tab 1', content: 'Content for Tab 1' },
        { name: 'Tab 2', content: 'Content for Tab 2' },
        { name: 'Tab 3', content: 'Content for Tab 3' },
      ],
      currentIndex: 0, // 默认选中第一个 Tab
    };
  },
  methods: {
    changeTab(index) {
      this.currentIndex = index;
    },
  },
};
</script>

<style>
/* 添加样式以突显选中的 Tab */
.active {
  font-weight: bold;
  color: blue;
  cursor: pointer;
}
</style>

  • 28
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

锅盖哒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值