vue3前一月/年+后一月/年
// 按钮文字
export const BUTTON_CONFIG = {
1: ["前一月", "后一月"],
2: ["前一年", "后一年"],
};
<template>
<div class="change-date flex-row">
<div
class="flex-center"
v-for="(item, index) in BUTTON_CONFIG[type]"
:key="item"
@click="handleDate(index)"
>
{{ item }}
</div>
</div>
</template>
<script setup name="changeDate">
import dayjs from "dayjs";
import { BUTTON_CONFIG } from "../consts/detail";
const props = defineProps({
// 类型 1-前一月,后一月 2-前一年,后一年
type: {
type: String,
default: "1",
},
// 日期
date: {
type: String,
default: "",
},
});
const emits = defineEmits(["update:date", "update"]);
// 切换日期
function handleDate(index) {
const { type, date } = props;
// 确定时间单位("month" 或 "year")
const unit = type === "1" ? "month" : "year";
// 计算增减的偏移量
const offset = index ? 1 : -1;
// 更新日期并格式化
const formattedDate = dayjs(date)
.add(offset, unit)
.format(type === "1" ? "YYYY-MM" : "YYYY");
emits("update:date", formattedDate);
emits("update");
}
</script>
<style lang="less" scoped>
.change-date {
width: 140px;
height: 36px;
margin-right: 20px;
background: #f1f1f1;
border-radius: 4px;
border: 1px solid #d5d5d5;
font-weight: 400;
font-size: 14px;
color: #6d6d6d;
line-height: 21px;
div {
width: 50%;
height: 100%;
cursor: pointer;
&:first-child {
border-right: 1px solid #d5d5d5;
}
&:hover {
color: #1f63ff;
}
}
}
</style>