Vue实现实时刷新时间的功能
作者:Lana学习中
这篇文章主要为大家详细介绍了如何Vue利用实现实时刷新时间的功能,文中的示例代码讲解详细,具有一定的借鉴价值,感兴趣的小伙伴可以了解下
前言
实现大屏的实时刷新时间的功能:在大屏中有时需要实现显示日期和当前的时间的功能,且秒数需要实时刷新。
实现方法
要点:每隔一秒刷新一次。
<div class="date">
{{ time.date }} {{ time.week }} {{ time.time }}
</div>
<script setup>
import { getTime } from '@/utils';
//获取并刷新日期
const time = ref('');
const getDataTime = () => {
time.value = getTime();
setTimeout(getDataTime, 1000);
};
onMounted(() => {
getDataTime();
});
</script>
//getTime方法
export function getTime() {
const nowDate = new Date()
const date = nowDate.getFullYear() + '-' + _formatNum(nowDate.getMonth() + 1) + '-' + _formatNum(nowDate.getDate())
const time = _formatNum(nowDate.getHours()) + ':' + _formatNum(nowDate.getMinutes()) + ':' + _formatNum(nowDate.getSeconds())
let week = ''
switch (nowDate.getDay()) {
case 0:
week = '星期天'
break
case 1:
week = '星期一'
break
case 2:
week = '星期二'
break
case 3:
week = '星期三'
break
case 4:
week = '星期四'
break
case 5:
week = '星期五'
break
case 6:
week = '星期六'
break
default:
break
}
return {
date,
time,
week
}
}
方法补充
vue获取当前时间并实时刷新
1、在data中声明变量
data() {
return {
nowDate: null, //存放年月日变量
nowTime: null, //存放时分秒变量
timer: "", //定义一个定时器的变量
currentTime: new Date(), // 获取当前时间
}
}
2、定义获取时间的方法getTime,并在created()声明周期里面调用,在实例创建前调用
created()
{
this.timer = setInterval(this.getTime, 1000);
}
3、具体方法如下:
methods: {
getTime(){
const date = new Date();
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const hour= date.getHours();
const minute = date.getMinutes();
const second = date.getSeconds();
const str = ''
if(this.hour>12) {
this.hour -= 12;
this.str = " PM";
}else{
this.str = " AM";
}
this.month=check(month);
this.day=check(day);
this.hour=check(hour);
this.minute=check(minute);
this.second=check(second);
function check(i){
const num = (i<10)?("0"+i) : i;
return num;
}
this.nowDate = year + "年" + this.month + "月" + this.day+"日";
this.nowTime = this.hour + ":" + this.minute + ":" + this.second + this.str;
},
}4、离开页面使用beforeDestroy() 销毁
beforeDestroy() {
if (this.timer) {
clearInterval(this.timer); // 在Vue实例销毁前,清除定时器
}
}
5、在页面需要显示的地方绑定{{ nowDate }},{{ nowTime }}即可
到此这篇关于Vue实现实时刷新时间的功能的文章就介绍到这了,更多相关Vue实时刷新时间内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
