likes
comments
collection
share

Vue2实现tab切换

作者站长头像
站长
· 阅读数 4

Vue2实现tab切换

以下代码实现了一个tab切换的功能,点击不同的tab会切换到对应的内容,并且选中的tab文字带下划线,下划线宽度比文字宽度短,并且与文字居中。

<template>
  <div>
    <div class="tabs">
      <div 
        v-for="(tab, index) in tabs" 
        :key="index" 
        class="tab" 
        :class="{ 'active': activeTab === index }"
        @click="activeTab = index"
      >
        {{ tab }}
        <div class="underline" v-if="activeTab === index"></div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tabs: ['Tab 1', 'Tab 2', 'Tab 3'],
      activeTab: 0
    }
  }
}
</script>

<style>
.tabs {
  display: flex;
  justify-content: space-around;
}

.tab {
  position: relative;
  padding: 10px;
  cursor: pointer;
}

.underline {
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 80%;
  height: 2px;
  background-color: black;
}

.active {
  font-weight: bold;
}

.active .underline {
  display: block;
}
</style>