Vue中 获取当前时间并实时刷新

您所在的位置:网站首页 vue实时更新时间 Vue中 获取当前时间并实时刷新

Vue中 获取当前时间并实时刷新

2023-10-30 00:07| 来源: 网络整理| 查看: 265

1. 实现代码 {{nowDate}}{{nowWeek}}{{nowTime}} 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); } } } 2. 实现效果

2020062310470442.png

3. 关于 Date 对象拓展

Date 对象用于处理日期和时间。

日期对象是用 new Date() 创建的。

实例化日期有四种方式:

var d = new Date(); var d = new Date(milliseconds); var d = new Date(dateString); var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);

Date 对象属性

属性描述constructor返回创建 Date 对象原型的函数。prototype允许您向对象添加属性和方法。

Date 对象方法

image.png



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3