vue3的简单的网页时钟功能

158 阅读1分钟

这个没有样式的,就是简单的显示年月日时分秒 封装成了一个组件,也可以弄成hooks,不过弄成hooks可能会导致父组件因为时间跳动而不断的重新渲染,触发更新

新人第一次发文章,想了想还是在掘金发吧,大佬们有不同意见评论区讨论,求轻喷

clock.vue

<template>
    <span>{{ currentTime }}</span>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { formatDate } from '@/utils';

const currentTime = ref('');
let timerId = null; // 用于存储定时器ID
let lastUpdate = 0; // 记录上次更新的时间戳

function updateTime() {
    const now = Date.now();
    if (!lastUpdate || now - lastUpdate >= 1000) {
        currentTime.value = formatDate(new Date());
        lastUpdate = now;
    }
}

function startTimer() {
    // requestAnimationFrame在网页不可见时会自动停止,也就是说这个网页时钟功能也会停止
    if (window.requestAnimationFrame) {
        function tick(timestamp) {
            updateTime(timestamp);
            // 检查是否需要继续请求下一帧
            if (lastUpdate === 0 || Date.now() - lastUpdate < 1000) {
                timerId = requestAnimationFrame(tick);
            }
        }
        timerId = requestAnimationFrame(tick);
    } else {
        function tick() {
            updateTime();
            timerId = setTimeout(tick, 1000); // 设置为每秒调用一次
        }
        tick(); // 初始化时立即调用一次
    }
}

function stopTimer() {
    if (window.requestAnimationFrame && timerId !== null) {
        cancelAnimationFrame(timerId);
    } else if (timerId !== null) {
        clearTimeout(timerId);
    }
}

onMounted(() => {
    startTimer();
});

onUnmounted(() => {
    stopTimer();
});
</script>

<style scoped></style>

这功能还是问的通义千问然后一起实现的 用requestAnimationFrame来实现的一个每秒刷新,因为requestAnimationFrame不是页面不可见的时候就停止调用了,还做了个兼容性处理,如果浏览器版本不支持就改成setTimeout递归调用(其实就是setInterval,哈哈)

哦还有引入的formateDate方法

function formatDate(cellValue) {
  if (cellValue == null || cellValue == "") return "";
  let date = new Date(cellValue);
  let year = date.getFullYear();
  let month =
    date.getMonth() + 1 < 10
      ? "0" + (date.getMonth() + 1)
      : date.getMonth() + 1;
  let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  let hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
  let minutes =
    date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
  let seconds =
    date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  return (
    year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds
  );
}