Vue3之简单tab使用

67 阅读1分钟

一、单文件组件使用:

<div style="margin-top: 50px;border:1px #909399 solid;width: 80%;height: 500px">
  <div class="tabs">
    <button
      v-for="(tab, index) in tabs"
      :key="index"
      :class="{ active: currentIndex === index }"
      @click="changeTab(index)"
    >
      {{ tab.title }}
    </button>
  </div>
  <div class="tab-content">
    <div v-show="currentIndex === index" v-for="(tab, index) in tabs" :key="index">
      {{ tab.content }}
    </div>
  </div>
</div>

js:

const tabs = ref([
  { title: 'Tab 1', content: 'Content for Tab 1' },
  { title: 'Tab 2', content: 'Content for Tab 2' },
  { title: 'Tab 3', content: 'Content for Tab 3' },
  { title: 'Tab 4', content: 'Content for Tab 4' }

])
const currentIndex = ref(0)
const changeTab = (index:any) => {
  currentIndex.value = index
}

css:

.tabs {
  display: flex;
  justify-content: space-around;
  margin-bottom: 10px;
}

.tabs button {
  padding: 10px 20px;
  border: none;
  background-color: #ccc;
  cursor: pointer;
}

.tabs button.active {
  background-color: #4CAF50; /* 激活状态的背景色 */
  color: white; /* 激活状态的文字颜色 */
}

.tab-content {
  padding: 20px;
  border: 1px solid #ccc;
}