<template>
  <div class="tab">
    <span
      v-for="({ title }, index) in Items"
      :key="`tab-${index}`"
      @click="e => click(e, index)"
      :class="{ curr: aIndex === index }"
      ref="tab"
    >
      {{ title }}
    </span>
    <div
      class="bar"
      :style="{ transform: `translateX(${barLeft}px)`, width: `${barWidth}px` }"
    ></div>
  </div>
</template>
<script lang="ts">
import { Component, Vue, Prop, Emit } from "vue-property-decorator";
@Component
export default class extends Vue {
  @Prop({
    required: true
  })
  private arr!: any[];
  private aIndex = 0;
  private barLeft = 0;
  private barWidth = 0;
  mounted() {
    (this.$refs.tab as HTMLElement[])[0].click();
  }
  get Items() {
    if (this.arr instanceof Array) return this.arr;
    if (typeof this.arr === "string")
      return (this.arr as string).split(",").map(title => ({ title }));
    return [];
  }
  @Emit("click")
  click({ target }: MouseEvent, index: number) {
    this.aIndex = index;
    const { offsetWidth, offsetLeft } = target as HTMLElement;
    this.barLeft = offsetLeft;
    this.barWidth = offsetWidth;
    return {
      index,
      item: this.Items[index]
    };
  }
}
</script>
<style lang="scss" scoped>
.tab {
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 2rem;
  padding: 0.5rem 0;
  position: relative;
  span {
    font-size: 2rem;
    font-weight: bolder;
    color: rgb(51, 51, 51);
    margin-right: 40px;
    cursor: pointer;
    &.hover,
    &.curr {
      color: #c52829;
    }
  }
  .bar {
    position: absolute;
    bottom: 0;
    left: 0;
    height: 0.2rem;
    background: #c52829;
    transition: all 0.5s;
  }
}
</style>
