在vue里,使用dayjs格式化时间并实现日期时间的实时更新
介绍
在 vue
里, 通过下载 dayjs
插件, 实现日期的格式化,并实时更新日期。
实现方式
- 下载 dayjs
使用命令:npm install dayjs
- 引入
命令:import dayjs from 'dayjs'
代码:
utils
里引入dayjs
,并格式化日期
// 引入 dayjs
import dayjs from 'dayjs';
// 格式化时间 年-月-日 时:分:秒
export const formatDate = () => {return dayjs().format('YYYY-MM-DD HH:mm:ss');
}
- 页面里引入
utils
里的formatDate
方法 ,并通过setInterval
实现,日期的实时更新
<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)})