首先呢 我们用new Date() 所展示的时间为

 推荐使用:第三方插件 dayjs

Day.js 是一个轻量的处理时间和日期的 JavaScript 库,和 Moment.js 的 API 设计保持完全一样. 如果您曾经用过 Moment.js, 那么您已经知道如何使用 Day.js

npm install dayjs --save

在xxx.vue中引入

<template>
  <h1>获取当前时间</h1>
  <div>{{ time }}</div>
</template>

<script setup>
import dayjs from "dayjs";

//没有使用dayjs
console.log(new Date());
//使用dayjs
console.log(dayjs(new Date()).format("YYYY-MM-DD hh:mm:ss"));
// 案例:动态获取当前时间
const time = ref();
const getTime = () => {
  time.value = dayjs(new Date()).format("YYYY-MM-DD hh:mm:ss");
};
var timer = 0;
onMounted(() => {
  timer = setInterval(() => {
    //设置定时器
    getTime(); //自定义事件
  }, 10);
});
onBeforeUnmount(() => {
  clearInterval(timer); //清除定时器
  timer = 0;
});
</script>

Logo

前往低代码交流专区

更多推荐