vue实现tab栏切换

vue实现tab栏切换并高亮显示的两种方式

非循环列表生成的按钮和盒子

实现效果如图
vue实现tab栏切换_第1张图片

  1. html部分代码
<div class="container">
    <div class="nav">
      <div class="btn" :class="{active : itemIndex == 1}" @click="btnClick(1)">苹果</div>
      <div class="btn" :class="{active : itemIndex == 2}" @click="btnClick(2)">杨桃</div>
      <div class="btn" :class="{active : itemIndex == 3}" @click="btnClick(3)">杨梅</div>
      <div class="btn" :class="{active : itemIndex == 4}" @click="btnClick(4)">荔枝</div>
    </div>
    <div class="detail">
      <div v-if="itemIndex == 1">我是苹果</div>
      <div v-if="itemIndex == 2">我是杨桃</div>
      <div v-if="itemIndex == 3">我是杨梅</div>
      <div v-if="itemIndex == 4">我是荔枝</div>
    </div>
  </div>

2.js部分

<script>
export default {
  data(){
    return{
      itemIndex:1
    }
  },
  methods:{
    btnClick(index){
      this.itemIndex =index
    }

  }
};
</script>

循环列表生成的
html部分

  <div class="container">
    <div class="nav">
      <div
        class="btn"
        :class="{ active: itemIndex == index }"
        v-for="(item, index) in btnList"
        :key="index"
        @click="btnClick(index)"
      >
        {{ item.name }}
      </div>
    </div>
    <div
      class="detail"
      v-for="(item, index) in btnList"
      :key="index"
      v-show="itemIndex == index"
    >
      {{ item.nameContent }}
    </div>
  </div>

js部分

<script>
export default {
  data() {
    return {
      itemIndex: 1,
      btnList: [
        {
          name: "苹果",
          nameContent: "我是苹果",
        },
        {
          name: "杨桃",
          nameContent: "我是杨桃",
        },
        {
          name: "杨梅",
          nameContent: "我是杨梅",
        },
        {
          name: "荔枝",
          nameContent: "我是荔枝",
        },
      ],
    };
  },
  methods: {
    btnClick(index) {
      this.itemIndex = index;
    },
  },
};
</script>

你可能感兴趣的:(vue,vue.js,javascript)