index.vue 2.33 KB
<template>
  <div class="tab-section"
       :class="{ isSticky }"
       :style="{ background: customBackground }">
    <div class="tab-slider" :style="tabSliderStyle"></div>
    <div v-for="item in normalizedList"
         :key="item.value"
         class="tab"
         :class="{ active: item.value === currentValue }"
         @click="handleSelect(item)">
      {{ item.label }}
    </div>
  </div>
</template>

<script>
export default {
	name: "DateTypeTabs",
	props: {
		value: {
			type: [String, Number],
			default: 0,
		},
		list: {
			type: Array,
			default() {
				return [
					{ label: "日", value: 0 },
					{ label: "周", value: 1 },
					{ label: "月", value: 2 },
				];
			},
		},
		isSticky: Boolean,
		customBackground: {
			type: String,
			default: "",
		},
	},
	computed: {
		normalizedList() {
			return (this.list || []).map((item, index) => {
				const value = item?.value;
				const label = item?.label;
				return {
					...item,
					label,
					value,
				};
			});
		},
		currentValue() {
			return this.value;
		},
		tabSliderStyle() {
			const tabCount = this.normalizedList.length || 1;
			const activeIndex = this.normalizedList.findIndex(item => item.value === this.currentValue);
			const currentIndex = activeIndex > -1 ? activeIndex : 0;
			return {
				width: `calc((100% - 4px) / ${tabCount})`,
				transform: `translateX(${currentIndex * 100}%)`,
			};
		},
	},
	methods: {
		handleSelect(item) {
			if (item.value === this.currentValue)
				return;
			this.$emit("input", item.value);
			this.$emit("change", item);
		},
	},
};
</script>

<style lang="scss" scoped>
.tab-section {
	position: relative;
	overflow: hidden;
	box-sizing: border-box;
	height: 28px;
	display: flex;
	align-items: center;
	background: #ffffff;
	border-radius: 28px;
	font-size: 12px;
	color: #999999;
	padding: 2px;
	flex-shrink: 0;

	.tab-slider {
		position: absolute;
		top: 2px;
		left: 2px;
		height: 24px;
		border-radius: 24px;
		background: #2c66f71a;
		transition: transform 0.25s ease;
	}

	&.isSticky {
		background: #f7f8fa;
	}

	.tab {
		position: relative;
		z-index: 1;
		flex: 1;
		text-align: center;
		font-weight: 500;
		font-size: 12px;
		height: 24px;
		border-radius: 24px;
		transition: color 0.25s ease;
		flex-shrink: 0;
		box-sizing: border-box;
		padding: 4px 0;
		&.active {
			color: #2c66f7;
			font-weight: 500;
		}
	}
}
</style>