<template>
<view class="data-pick scroll-container">
<!-- 日期项 -->
<view
class="date-item"
v-for="(item, index) in weekDates"
:key="index"
:id="`date-${index}`"
:class="{ active: selectedDate === item.date }"
@click="handleDateClick(item.date, index)"
>
<text class="weekday">{ { item.weekday }}</text>
<text class="date">{ { item.date }}</text>
</view>
</view>
</template>
<script setup>
import { ref, onMounted } from "vue";
const props = defineProps({
// 初始化的周数据
weekDates: {
type: Array,
required: true,
},
});
const emit = defineEmits(["dateSelected"]);
// 选中的日期
const selectedDate = ref("");
// 点击日期事件
const handleDateClick = (date, index) => {
selectedDate.value = date;
emit("dateSelected", date); // 向父组件发送选中日期
const container = document.querySelector(".scroll-container");
const clickedElement = document.getElementById(`date-${index}`);
if (!container || !clickedElement) return;
const containerWidth = container.offsetWidth;
const containerScrollLeft = container.scrollLeft;
const elementLeft = clickedElement.offsetLeft;
const elementWidth = clickedElement.offsetWidth;
const elementRight = elementLeft + elementWidth;
const offset = 200;
if (elementLeft < containerScrollLeft) {
container.scrollTo({
left: elementLeft - offset,
behavior: "smooth",
});
} else if (elementRight > containerScrollLeft + containerWidth) {
const scrollToPosition = elementRight - containerWidth + offset;
container.scrollTo({
left: scrollToPosition,
behavior: "smooth",
});
}
};
// 设置默认选中的日期为今天
onMounted(() => {
const today = new Date().toISOString().split("T")[0]; // 获取当前日期(格式:YYYY-MM-DD)
const todayItem = props.weekDates.find((item) => item.date === today);
if (todayItem) {
selectedDate.value = todayItem.date; // 如果今天在 weekDates 中,设置为选中状态
}
});
</script>