使用的是moment.js插件

关键字 vue3的 onMounted 和 onBeforeUnmount 声明周期 一个用来创建 一个用来销毁
创建什么呢? setInterval 函数 销毁时使用时 clearInterval清除定时器
1
上代码
- function formatTime() {
- const date = moment();
- const year = date.year();
- const month = date.month() + 1;
- const day = date.date();
- const hour = date.hours();
- const minute = date.minutes();
- const second = date.seconds();
- const weekday = date.day();//使用day()获取星期几
- const week = switchWeek(weekday); //使用字典函数查找替换对应的星期几
- return `${year}.${formatTwoDigits(month)}.${formatTwoDigits(day)} ${week} ${formatTwoDigits(hour)}:${formatTwoDigits(minute)}:${formatTwoDigits(second)}`;
- }
-
- //星期转换
- function switchWeek(days) {
- var res;
- if (days == 0) {
- res = "星期日"
- }
- if (days == 1) {
- res = "星期一"
- }
- if (days == 2) {
- res = "星期二"
- }
- if (days == 3) {
- weeks = "星期三"
- }
- if (days == 4) {
- res = "星期四"
- }
- if (days == 5) {
- res = "星期五"
- }
- if (days == 6) {
- res = "星期六"
- };
- return res;
- }
- //补零函数
- function formatTwoDigits(n) {
- if (n < 10) {
- return '0' + n;
- } else {
- return n;
- }
- }
现在已经能拿到对应的当前时间的数据了 但是没办法使用实时更新 所以就要用到
-
- const monthTime = ref(null)
- //将setInterval函数赋予timeChange 变量等下好关闭使用
- const timeChange = ref(null)
-
- //生命周期函数
- onMounted(() => {
- const timerId = setInterval(() => {
- //将值时间赋予monthTime变量
- monthTime.value = formatTime();
- }, 1000);
- timeChange.value = timerId;
- })
-
- // 销毁生命周期
- onBeforeUnmount(() => {
- if (timeChange) {
- clearInterval(timeChange);
- }
- });
页面就直接使用就行
{{monthTime}}
vue2版本看这个 vue2版本