要使用 Vue 组件实现动态刷新时间效果,你可以在组件的 mounted
钩子函数中设置一个定时器,以每隔一定时间更新显示的时间。下面是一个简单的示例代码:
<template>
<div>
<p>当前时间:{
{ formattedTime }}</p>
</div>
</template>
<script>
export default {
data() {
return {
formattedTime: ''
};
},
mounted() {
this.updateTime(); // 初始化时先更新时间
this.timer = setInterval(this.updateTime, 1000); // 每隔一秒更新一次
},
beforeDestroy() {
clearInterval(this.timer); // 组件销毁时清除定时器
},
methods: {
updateTime() {
const now = new Date();
const year = now.getFullYear();
const month = this.padZero(now.getMonth() + 1);
const day = this.padZero(now.getDate());
const hours = this.padZero(now.getHours());
const minutes = this.padZero(now.getMinutes());
const seconds = this.padZero(now.getSeconds());
this.formattedTime = `${year}年${month}月${day}日 ${hours}时${minutes}分${seconds}秒`;
},
padZero(value) {
return value.toString().padStart(2, '0');
}
}
};
</script>
在上面的代码中,我们定义了 formattedTime
作为显示格式化后的时间的数据属性。在 updateTime
方法中,我们获取当前时间的年、月、日、时、分、秒,并使用模板字符串拼接成指定的格式。
为了确保月、日、时、分、秒的值始终显示为两位数(例如:01、02、...、09、10、...、12、...等等),我们还定义了一个辅助函数 padZero
,它会在数字小于 10 时,在其前面补零。