hsy
5 天以前 fee2f2532144fca6c81b1523aeef54165c5263b2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<script setup lang="ts">
import type { SegmentedItem } from './types';
 
import { computed } from 'vue';
 
import { TabsTrigger } from 'reka-ui';
 
import { cn } from '../../../../../base/shared/src/utils';
 
import { Tabs, TabsContent, TabsList } from '../../ui';
import TabsIndicator from './tabs-indicator.vue';
 
interface Props {
  defaultValue?: string;
  tabs?: SegmentedItem[];
  /** 是否允许横向滚动:tab 较多时启用,各 tab 按内容宽度排列,超出部分可滑动 */
  scrollable?: boolean;
}
 
const props = withDefaults(defineProps<Props>(), {
  defaultValue: '',
  tabs: () => [],
  scrollable: false,
});
 
const activeTab = defineModel<string>();
 
const getDefaultValue = computed(() => {
  return props.defaultValue || props.tabs[0]?.value;
});
 
const tabsStyle = computed(() => {
  if (props.scrollable) {
    return undefined;
  }
  return {
    'grid-template-columns': `repeat(${props.tabs.length}, minmax(0, 1fr))`,
  };
});
 
const tabsIndicatorStyle = computed(() => {
  if (props.scrollable) {
    return undefined;
  }
  return {
    width: `${(100 / props.tabs.length).toFixed(0)}%`,
  };
});
 
function activeClass(tab: string): string[] {
  return tab === activeTab.value ? ['font-bold!', 'text-primary'] : [];
}
</script>
 
<template>
  <Tabs v-model="activeTab" :default-value="getDefaultValue">
    <TabsList
      :style="tabsStyle"
      :class="
        cn(
          'bg-accent outline-heavy! relative outline-2!',
          // 可滚动模式:左对齐(覆盖 reka-ui 的 justify-center,否则内容超宽时左侧被挤出且无法滚动)、全宽、横向滚动
          scrollable
            ? 'flex! w-full! overflow-x-auto justify-start!'
            : 'grid w-full',
        )
      "
    >
      <TabsIndicator v-if="!scrollable" :style="tabsIndicatorStyle" />
      <template v-for="tab in tabs" :key="tab.value">
        <TabsTrigger
          :value="tab.value"
          :class="activeClass(tab.value)"
          class="hover:text-primary z-20 inline-flex shrink-0 items-center justify-center rounded-md px-2 py-1 text-sm font-medium whitespace-nowrap disabled:pointer-events-none disabled:opacity-50"
        >
          {{ tab.label }}
        </TabsTrigger>
      </template>
    </TabsList>
    <template v-for="tab in tabs" :key="tab.value">
      <TabsContent :value="tab.value">
        <slot :name="tab.value"></slot>
      </TabsContent>
    </template>
  </Tabs>
</template>