CSS + JS + Vue 实现仿 Tabs 功能

207 阅读1分钟

在许多应用中,Tabs 组件是一种常见的 UI 元素,用于在不同的内容区域之间进行切换。以下是使用 Vue.js、CSS 和 JavaScript 实现 Tabs 功能的一个简单示例。

Vue 组件

创建一个 Tabs.vue 组件:

<template>
  <div>
    <div class="tabs-header">
      <button
        v-for="(tab, index) in tabs"
        :key="index"
        :class="{ active: activeTab === index }"
        @click="switchTab(index)"
      >
        {{ tab.label }}
      </button>
    </div>
    <div class="tabs-content">
      <div v-if="activeTab === index" v-for="(tab, index) in tabs" :key="index">
        {{ tab.content }}
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeTab: 0, // 当前激活的标签索引
      tabs: [
        { label: 'Tab 1', content: 'This is Tab 1 content' },
        { label: 'Tab 2', content: 'This is Tab 2 content' },
        { label: 'Tab 3', content: 'This is Tab 3 content' },
      ],
    };
  },
  methods: {
    // 切换标签
    switchTab(index) {
      this.activeTab = index;
    },
  },
};
</script>

<style scoped>
.tabs-header {
  display: flex;
  border-bottom: 2px solid #ccc;
}

button {
  padding: 10px;
  cursor: pointer;
  border: none;
  background: none;
  border-bottom: 2px solid transparent;
}

button.active {
  border-bottom: 2px solid blue;
}
</style>

解释

  1. 数据和状态: 我们有一个 activeTab 来追踪哪个标签是当前激活的,还有一个 tabs 数组用于存放所有的标签及其内容。

  2. 标签头和标签内容: 在模板中,我们分别用两个 div 创建了标签头 (tabs-header) 和标签内容 (tabs-content)。

  3. 切换标签: 我们定义了一个 switchTab 方法,当用户点击标签时会调用这个方法,该方法会更新 activeTab 的值。

  4. 活动标签样式: 我们用 Vue 的类绑定功能来动态添加一个 active 类,这样当前激活的标签就会有一个特殊的底部边框。

这个组件实现了基础的 Tabs 功能,你可以根据需要进行更多定制和扩展。希望这个示例能帮助你实现你需要的功能!