vue3中,封装时间组件,包含年月日、时分秒、星期
效果
代码
组件代码
src\layout\Header\components\timeModal.vue
<template>
<div class="date-box">
<div class="date-time">{{ dateObj.time }}</div>
<div class="date-date">
{{ dateObj.date }} <span class="date-day">| {{ dateObj.week }}</span>
</div>
<!-- <div class="date-day">{{ dateObj.week }}</div> -->
<div class="date-logo"></div>
</div>
</template>
<script setup lang="ts" name="timeModal">
import { dateFormat, FormatsEnums } from "@/utils/util";
import { onMounted, reactive } from "vue";
interface IDate {
time: string;
week: string;
date: string;
timer: number;
}
const dateObj: IDate = reactive({
time: "--:--:--",
date: "----/--/--",
week: "--",
timer: 0
});
const weekList = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"];
const getTime = () => {
dateObj.time = dateFormat(0, FormatsEnums.TIME);
dateObj.date = dateFormat(0, FormatsEnums.YMD);
let weekDay = new Date().getDay();
dateObj.week = weekList[weekDay - 1];
// console.log(time);
};
onMounted(() => {
dateObj.timer = window.setInterval(() => {
getTime();
}, 1000);
});
</script>
<style scoped lang="scss">
@import "./index.scss";
</style>
src\utils\util.ts
export enum FormatsEnums {
YMD = "Y-m-d",
YMDHIS = "Y-m-d H:i:s",
_YMD = "Y年m月d日",
_YMDHIS = "Y年m月d日 H时i分",
TIME = "H:i:s"
}
export const dateFormat = function (timestamp: number, formats: FormatsEnums): string {
// formats格式包括
// 1. Y-m-d
// 2. Y-m-d H:i:s
// 3. Y年m月d日
// 4. Y年m月d日 H时i分
formats = formats || "Y-m-d";
const zero = function (value: number): string | number {
if (value < 10) {
return "0" + value;
}
return value;
};
const myDate = timestamp ? new Date(timestamp) : new Date();
const year = myDate.getFullYear();
const month = zero(myDate.getMonth() + 1);
const day = zero(myDate.getDate());
const hour = zero(myDate.getHours());
const minite = zero(myDate.getMinutes());
const second = zero(myDate.getSeconds());
return formats.replace(/Y|m|d|H|i|s/gi, function (matches: string): any {
return {
Y: year,
m: month,
d: day,
H: hour,
i: minite,
s: second
}[matches];
});
};
页面引用
src\layout\Header\index.vue
<template>
<div class="header">
<div class="header-left"><TimeModal></TimeModal></div>
</div>
</template>
<script setup lang="ts">
import TimeModal from "./components/timeModal.vue";
</script>
<style scoped lang="scss">
@import "./index.scss";
</style>
src\layout\Header\index.scss
.header {
position: relative;
box-sizing: border-box;
display: flex;
align-items: center;
width: 100%;
height: 96px;
padding: 0 48px;
box-shadow: 0 2px 2px rgb(0 0 0 / 25%);
.header-left {
margin-right: auto;
}
}