在Vue 3 中,你可以使用 JavaScript 的 Date 对象来获取当前的时分秒。以下是一个简单的示例,展示了如何在 Vue 组件中获取当前的时分秒:
<template>
<div>
<p>当前时间:{{ currentTime }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue';
const currentTime = ref('');
// 更新当前时间
setInterval(() => {
const now = new Date();
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
const seconds = String(now.getSeconds()).padStart(2, '0');
currentTime.value = `${hours}:${minutes}:${seconds}`;
}, 1000);
</script>
在上面的示例中,我们首先引入了 Vue 3 中提供的 `ref` 函数,用于创建一个响应式的变量 `currentTime`。然后使用 `setInterval` 函数每秒更新一次 `currentTime` 的值,通过 `new Date()` 获取当前的日期时间,然后从中提取小时、分钟和秒,并使用 `padStart` 方法补齐不足两位的数字。最后将格式化后的时间赋值给 `currentTime`。
在模板中,我们直接使用 `{{ currentTime }}` 来显示当前时间。