<!-- 标签栏组件 -->
<template>
  <div class="mtp-tabbar">
    <ul class="tabs" v-if="dataSource.length">
      <li :class="['tabs-item', dataIndex === index && 'active']" v-for="(item,index) in dataSource" :key="index" @click="onChange(index)">
        {{ label ? item[label] : '标签' + index }}
      </li>
    </ul>
    <slot></slot>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, watch } from 'vue';

export default defineComponent({
  emits: ['update:selectedIndex', 'change'],
  props: {
    dataSource: {
      type: Array,
      default: () => ([]),
    },
    // 绑定的标签属性名
    label: String,
    // 默认选中的标签索引
    selectedIndex: {
      type: Number,
      default: 0,
    }
  },
  setup(props, { emit }) {
    const dataIndex = ref(props.selectedIndex);

    const onChange = (index: number) => {
      if (dataIndex.value !== index) {
        dataIndex.value = index;
        emit('update:selectedIndex', index);
        emit('change', props.dataSource[index], index);
      }
    }

    watch(() => props.selectedIndex, (val) => {
      dataIndex.value = val;
    })

    return {
      dataIndex,
      onChange
    }
  }
})
</script>

<style lang="less">
@import './index.less';
</style>