Vue 中获取当前时间并实时刷新的实现代码

时间:2021-05-26

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 中获取当前时间并实时刷新的实现代码的文章就介绍到这了,更多相关vue获取当前时间实时刷新内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章