follow-tab-block.vue 2.06 KB
<template>
  <div class="tab-block">
    <div v-for="(tab, index) in tabList" :key="index" :ref="'tab-item' + index" class="tab-item" :class="{active: index == activeIndex}"  @click="changeType(index)">
      {{tab.name}}
      <div v-if="index == statusBlockIndex" ref="statusBlock" class="tab-status-block" :style="statusBlockStyle"></div>
    </div>
  </div>
</template>

<script>
import {findIndex} from 'lodash';

export default {
  props: {
    activeType: {
      type: Number,
      default: -1
    }
  },
  data() {
    let tabList = [
      {name: '用户', type: 1},
      {name: '话题', type: 0},
    ];

    let index = Math.max(findIndex(tabList, {type: this.activeType}), 0);

    return {
      tabList,
      statusBlockIndex: index,
      activeIndex: index,
      statusBlockStyle: {}
    };
  },
  watch: {
    activeType(val) {
      let index = findIndex(this.tabList, {type: val});

      if (index > -1) {
        this.activeIndex = index;
      }
    },
    activeIndex() {
      this.changeStatusBlockStyle();
    }
  },
  methods: {
    changeType(index) {
      this.activeIndex = index;
      this.$emit('on-change-tab', {...this.tabList[index]});
    },
    changeStatusBlockStyle() {
      const baseDom = this.$refs['tab-item' + this.statusBlockIndex];

      if (baseDom) {
        const baseLeft = baseDom[0].offsetLeft;
        const {offsetLeft, offsetWidth} = this.$refs['tab-item' + this.activeIndex][0] || {};

        this.statusBlockStyle = {
          transform: `translate3d(${offsetLeft - baseLeft}px, 0, 0)`,
          width: offsetWidth + 'px'
        };
      }
    }
  }
};
</script>

<style scoped lang="scss">
.tab-block {
  height: 80px;
  background-color: #fff;
  display: flex;
  justify-content: center;
  font-size: 32px;

  .tab-item {
    margin: 0 38px;
    padding-top: 20px;
    color: #b0b0b0;
    position: relative;

    &.active {
      color: #222;
      font-weight: 500;
    }
  }

  .tab-status-block {
    width: 100%;
    height: 6px;
    background: #222;
    position: absolute;
    bottom: -1px;
    transition: all 300ms;
  }
}
</style>