第一种方式:静态
<template>
<div class="time">
创建时间:{{ date }}
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
const date = ref('')
//格式化时间的函数 。它接受一个数字类型的参数 time,表示需要格式化的时间。
// 时间补零
function formatTime(time: number) {
return time < 10 ? `0${time}` : time
}
function updateTime() {
const now = new Date()
const year = now.getFullYear() //年
const month = now.getMonth() + 1 //月
const day = now.getDate() //日
const hours = now.getHours() //小时
const minutes = now.getMinutes() //分钟
const seconds = now.getSeconds() //秒
const week = ["星期日", "星期一", "星期二", "星期三", "星期四",
"星期五", "星期六"] [now.getDay()] //星期
//需要展示的内容 对应的展示即可
date.value = `${year}-${formatTime(month)}-${formatTime(day)} ${formatTime(hours)}:${formatTime(minutes)}:${formatTime(seconds)} ${week}`
}
onMounted(() => {
updateTime()
})
</script>
第二种方式:实时更新
<template>
<div>
<p>当前时间: {{ currentTime }}</p>
</div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
const currentTime = ref(new Date().toLocaleTimeString());
let intervalId = null;
const updateTime = () => {
currentTime.value = new Date().toLocaleTimeString();
};
onMounted(() => {
intervalId = setInterval(updateTime, 1000);
});
onUnmounted(() => {
clearInterval(intervalId);
});
</script>
Wish I could help you!