使用Vue.js将DigitalClock组件24小时制转换为带AM/PM的12小时制
DigitalClock.vue 12小时制带AM/PM实现方案 核心修改逻辑是对24小时制的小时数做转换,同时匹配对应的时段标识即可,以下是不同Vue版本的可运行实现:
Vue3 语法实现
<template> <div class="digital-clock"> <span>{{ formattedTime }}</span> </div> </template> <script setup> import { ref, onMounted, onUnmounted } from 'vue' const formattedTime = ref('') let timer = null const updateTime = () => { const now = new Date() let hours = now.getHours() // 判定上下午标识 const period = hours >= 12 ? 'PM' : 'AM' // 转换为12小时制,处理12点、0点特殊场景 hours = hours % 12 || 12 // 分钟、秒补前导零 const minutes = String(now.getMinutes()).padStart(2, '0') const seconds = String(now.getSeconds()).padStart(2, '0') formattedTime.value = `${hours}:${minutes}:${seconds} ${period}` } onMounted(() => { updateTime() // 每秒更新时间 timer = setInterval(updateTime, 1000) }) onUnmounted(() => { clearInterval(timer) }) </script> <style scoped> .digital-clock { font-size: 2rem; font-weight: 700; } </style>
Vue2 语法实现
<template> <div class="digital-clock"> <span>{{ formattedTime }}</span> </div> </template> <script> export default { data() { return { formattedTime: '', timer: null } }, mounted() { this.updateTime() this.timer = setInterval(this.updateTime, 1000) }, beforeDestroy() { clearInterval(this.timer) }, methods: { updateTime() { const now = new Date() let hours = now.getHours() const period = hours >= 12 ? 'PM' : 'AM' hours = hours % 12 || 12 const minutes = String(now.getMinutes()).padStart(2, '0') const seconds = String(now.getSeconds()).padStart(2, '0') this.formattedTime = `${hours}:${minutes}:${seconds} ${period}` } } } </script>
内容的提问来源于stack exchange,提问作者Jcc
相关产品推荐
相关产品推荐

