在vue里,使用dayjs格式化时间并实现日期时间的实时更新

介绍

在 vue里, 通过下载 dayjs 插件, 实现日期的格式化,并实时更新日期。

实现方式

  1. 下载 dayjs
    使用命令: npm install dayjs
  2. 引入
    命令: import dayjs from 'dayjs'

代码:

  1. utils里引入 dayjs,并格式化日期
javascript 复制代码
// 引入 dayjs
import dayjs from 'dayjs';
// 格式化时间  年-月-日 时:分:秒
export const formatDate = () => {
  return dayjs().format('YYYY-MM-DD HH:mm:ss');
}
  1. 页面里引入 utils里的 formatDate 方法 ,并通过 setInterval 实现,日期的实时更新
javascript 复制代码
<div>{{currentTime}}</div>
// 引入 formatDate 
import {  formatDate } from "@/utils/index.js";
import { ref, onMounted ,onUnmounted} from 'vue'
const currentTime = ref('');
let timer = null
const updateTime = () => {
  // 更新 tableData 中的第一行数据
  currentTime.value = formatDate();
}
onMounted(() => {
  // 初始化的时候立即更新一次
  updateTime();
  timer = setInterval(updateTime, 1000)
})
  onUnmounted(() => {
    clearInterval(timer)
  })
相关推荐
薛定谔的猫-菜鸟程序员3 小时前
Electron开发超详细教程(从入门到放弃)
前端·javascript·electron
最强小杰3 小时前
DeepSeek V4 Flash + Codex CLI 接入教程:原生 Responses API 适配,从配置到跑通收藏这篇就够了(2026)
java·前端·python·ai
静水leo4 小时前
使用 Whistle 拦截接口并模拟后端响应
前端
掘金者阿豪4 小时前
SQL Server数据迁移完成后,凌晨的数据库告警该怎么查?
前端·后端
小郎君6584 小时前
Vue 多标签页的加载态设计:为什么我没有用 Suspense 实现 PageLoading
vue.js·算法
JudithHuang4 小时前
React 嵌套路由与布局
前端·react.js·arcgis·react·react router
htzyl2064 小时前
前端阶梯——第四十三章、实战二:待办清单To-Do
前端·javascript·html
yilaisai4 小时前
前端开发遇到的一些细节问题整理
vue.js
程序员大阳4 小时前
HTML+CSS+JS对话式实战(1)-开篇:认识我们要做的社团活动发布平台
javascript·css·html·实战·系统·平台·社团活动发布