小编这次要给大家分享的是Vue中怎么获取当前时间并实时刷新,文章内容丰富,感兴趣的小伙伴可以来了解一下,希望大家阅读完这篇文章之后能够有所收获。
1. 实现代码
<template>
<div>
{{nowDate}}{{nowWeek}}{{nowTime}}
</div>
</template>
<script>
export default {
data(){
return {
nowDate: "", // 当前日期
nowTime: "", // 当前时间
nowWeek: "" // 当前星期
}
},
methods:{
dealWithTime(data) { // 获取当前时间
let formatDateTime;
let Y = data.getFullYear();
let M = data.getMonth() + 1;
let D = data.getDate();
let H = data.getHours();
let Min = data.getMinutes();
let S = data.getSeconds();
let W = data.getDay();
H = H < 10 ? "0" + H : H;
Min = Min < 10 ? "0" + Min : Min;
S = S < 10 ? "0" + S : S;
switch (W) {
case 0:
W = "日";
break;
case 1:
W = "一";
break;
case 2:
W = "二";
break;
case 3:
W = "三";
break;
case 4:
W = "四";
break;
case 5:
W = "五";
break;
case 6:
W = "六";
break;
default:
break;
}
this.nowDate = Y + "年" + M + "月" + D + "日 ";
this.nowWeek = "周" + W ;
this.nowTime = H + ":" + Min + ":" + S;
// formatDateTime = Y + "年" + M + "月" + D + "日 " + " 周" +W + H + ":" + Min + ":" + S;
},
},
mounted() {
// 页面加载完后显示当前时间
this.dealWithTime(new Date())
// 定时刷新时间
this.timer = setInterval(()=> {
this.dealWithTime(new Date()) // 修改数据date
}, 500)
},
destroyed() {
if (this.timer) { // 注意在vue实例销毁前,清除我们的定时器
clearInterval(this.timer);
}
}
}
</script>
<style lang="scss" scope>
</style>
2. 实现效果
看完这篇关于Vue中怎么获取当前时间并实时刷新的文章,如果觉得文章内容写得不错的话,可以把它分享出去给更多人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。