没什么话想说的,show code!(其实很烂)
代码冗余也懒得改了…
封装: hook > useTime.ts
import {
ref, reactive, onMounted, onUnmounted } from 'vue'
/**
* 如果当前分钟和秒钟是小于10的话,前面加一个 0
*
* */
export default function useTime() {
let now = reactive(new Date())
let hour = ref<string>(now.getHours().toString())
let minute = ref<string>(now.getMinutes() < 10 ? '0' + now.getMinutes().toString() : now.getMinutes().toString())
let second = ref<string>(now.getSeconds() < 10 ? '0' + now.getSeconds().toString() : now.getSeconds().toString()
)
let timer: null | NodeJS.Timer = null
onMounted(() => {
timer = setInterval(() => {
now = new Date()
hour.value = now.getHours().toString()
minute.value = now.getMinutes() < 10 ? '0' + now.getMinutes().toString() : now.getMinutes().toString()
second.value = now.getSeconds() < 10 ? '0' + now.getSeconds().toString() : now.getSeconds().toString()
}, 1000)
})
onUnmounted(() => {
clearInterval(timer ? timer : '')
})
return [ hour, minute, second ]
}
在组件中使用
<script setup lang="ts">
import useTime from '../hooks/useTime'
const [hour, minute, second] = useTime()
</script>
<template>
<h3>现在是北京时间:{
{hour}}: {
{minute}}: {
{second}}</h3>
</template>
<style>
</style>