vue中如何实现tab切换

459 阅读1分钟
  • 点击第一个按钮,隐藏其他div.显示第一个div.让第一个按钮变红,其他按钮变白
  • 点击第二个按钮,隐藏其他div.显示第二个div.让第二个按钮变红,其他按钮变白
  • 点击第三个按钮,隐藏其他div.显示第一个div.让第三个按钮变红,其他按钮变白
  • ..........

-- 点击某个选项卡并显示它对应的内容

1、简单实现tab切换

<template>
  <div style="width: 200px;">
    <ul class="ul">
    //tab标签
      <li
        v-for="(item,index) in tabs"
        :key="index"
        :class="activeId==index?'active':''"
        @click="change(index)"
      >{{item}}</li>
    </ul>
    //tab页面内容
    <div
      v-for="(item,index) in tabs"
      :key="index"
    >
      <span v-show="activeId==index">{{item}}</span>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      tabs: ["tab1", "tab2", "tab3"],
      activeId: 0,
    };
  },
  methods: {
    change(index) {
      this.activeId = index;
    },
  },
};
</script>
<style>
.ul {
  list-style: none;
  display: flex;
  justify-content: space-evenly;
}
.ul:hover {
  cursor: pointer;
}
.active {
  border: 1px solid red;
}
</style>

2、使用 component 动态组件实现 Tab切换

<template>
  <div style="width: 200px;">
    <ul class="ul">
      <li
        v-for="(item,index) in tabs"
        :key="index"
        :class="activeId==index?'active':''"
        @click="change(index)"
      >{{item}}</li>
    </ul>
    <component :is="currentView"></component>
  </div>
</template>
<script>
import initOne from "./tabSt/initOne.vue";
import initTwo from "./tabSt/initTwo.vue";
import initThree from "./tabSt/initThree.vue";

export default {
  components: {
    initOne,
    initTwo,
    initThree,
  },
  data() {
    return {
      tabs: ["tab1", "tab2", "tab3"],
      activeId: 0,
      currentView: "initOne",
    };
  },
  methods: {
    change(index) {
      this.activeId = index;
      switch (index) {
        case 0:
          {
            this.currentView = initOne;
          }
          break;
        case 1:
          {
            this.currentView = initTwo;
          }
          break;
        case 2:
          {
            this.currentView = initThree;
          }
          break;
      }
    },
  },
};
</script>
<style>
.ul {
  list-style: none;
  display: flex;
  justify-content: space-evenly;
}
.ul:hover {
  cursor: pointer;
}
.active {
  border: 1px solid red;
}
</style>

效果图:

233.gif