Vue实现 Tab 标签切换效果(含选中状态)

父组件

<template>
  <div class="container">
    <div class="tabs">
      <div
        class="tab"
        v-for="(item,index) in tabs"
        :class="{selected:isSelected==index}"
        :key="index"
        @click="toggleTab(item.name,index)"
      >
{{item.title}}</div>
    </div>
    <component
      :is="currentTab"
      keep-alive
    >
    </component>
  </div>
</template>

<script>
// 引入子组件
import One from './components/One'
import Two from './components/Two'
import Three from './components/Three'
export default {
  name: 'Test',
  data () {
    return {
      currentTab: 'One', // 当前选中且显示在页面中的子组件
      isSelected: 0, // 当前选中的下标,用于设置选中样式
      tabs: [
        {name: 'One', title: 'one'},
        {name: 'Two', title: 'two'},
        {name: 'Three', title: 'three'}
      ]
    }
  },
  components: { // 声明子组件
    One,
    Two,
    Three
  },
  methods: {
    toggleTab: function (tab, index) {
      this.currentTab = tab // tab为当前触发选中的组件名
      this.isSelected = index
    }
  }
}
</script>
<style lang="stylus" scoped>
.container {
}

.tabs {
  display: flex;
  text-align: center;
}

// tab 默认样式
.tab {
  width: calc((100% / 3));
  touch-action: none;
}

// tab 被选中样式
.selected {
  background-color: red;
}
</style>

1.子组件components/One.vue

<template>
  <div class="container">1</div>
</template>
<script>
export default {
  name: 'One'
}
</script>
<style lang="stylus" scoped></style>

2.子组件components/Two.vue

<template>
  <div class="container">2</div>
</template>
<script>
export default {
  name: 'Two'
}
</script>
<style lang="stylus" scoped></style>

3.子组件components/Three.vue

<template>
  <div class="container">3</div>
</template>
<script>
export default {
  name: 'Three'
}
</script>
<style lang="stylus" scoped></style>
Last modification:April 25th, 2019 at 10:03 pm
如果觉得我的文章对你有用,请随意赞赏

Leave a Comment