Vue3实时更新时间(年-月-日 时:分:秒)

代码案例

复制代码
<script lang="ts" setup>
import { ref,onMounted } from 'vue';
const timer = ref()
const date = ref("")//年月日
const moreTime = ref("")//时分秒
onMounted(()=>{
    //创建定时器1秒执行一次
    timer.value = setInterval(() => {
        formateDate()
    }, 1000)
})
//取消定时器
onBeforeUnmount(() => {
    clearInterval(timer.value) //清除定时器
})
//获取当前时间
const formateDate = () => {
    const time = new Date()
    const year = time.getFullYear()
    const month = complement(time.getMonth() + 1)
    const day = complement(time.getDate())
    const hour = complement(time.getHours())
    const minute = complement(time.getMinutes())
    const second = complement(time.getSeconds())
    moreTime.value = `${hour}:${minute}:${second}`
    date.value = `${year}-${month}-${day}`
}
//当时间为个位数的时候,在数字前加0
const complement = (value: number): string => {
    return value < 10 ? `0${value}` : value.toString()
}
</script>

运行结果

相关推荐
mCell5 小时前
GSAP ScrollTrigger 详解
前端·javascript·动效
gnip5 小时前
Node.js 子进程:child_process
前端·javascript
excel9 小时前
为什么在 Three.js 中平面能产生“起伏效果”?
前端
excel10 小时前
Node.js 断言与测试框架示例对比
前端
天蓝色的鱼鱼11 小时前
前端开发者的组件设计之痛:为什么我的组件总是难以维护?
前端·react.js
codingandsleeping11 小时前
使用orval自动拉取swagger文档并生成ts接口
前端·javascript
石金龙12 小时前
[译] Composition in CSS
前端·css
白水清风12 小时前
微前端学习记录(qiankun、wujie、micro-app)
前端·javascript·前端工程化
Ticnix12 小时前
函数封装实现Echarts多表渲染/叠加渲染
前端·echarts
用户221520442780012 小时前
new、原型和原型链浅析
前端·javascript