这两天在写地图项目,有一个需求为实时显示现在的时间,原来我写的代码有一点问题就是刷新了时间才会更新,而不是实时更新,在网上查阅了一些博客,感觉部分同学写的不是很对,于是便有了这篇博客
先来看效果图:
下面展示具体的代码:
vue的template部分
<div class = "left"><p>{{ time }}</p><p>{{ date }} {{ weekday }}</p></div>
<div class = "right"><p>{{ city }}</p><p>{{ weather }}</p></div>
<div class = "bottom">
<div v-for = "(item,index) in threeDays" :key = "index">
<p>{{ days[index] }}</p>
<p>{{ item.type }}</p>
<p>{{ item.low }}/{{ item.high }}</p>
</div>
</div>
vue的 script部分
import {getCurrentTime , getCurrentDate , getCurrentWeek} from '../utils/time'
data(){
return {
time:'',
date:'',
weekday:'',
}
}
created(){
getThree(){
let that = this;
that.timer3 = setInterval(() => {
that.date = getCurrentDate(0,new Date());
that.days = [];
for(let i = 1;i <= 3;i++){
that.days.push(getCurrentDate(i,new Date()));
}
},1000)
},
getCurrent(){
let that = this;
that.timer1 = setInterval(() => {
that.time = getCurrentTime(new Date());
},1000)
},
getCurrentWeekday(){
let that = this;
that.timer2 = setInterval(() => {
that.weekday = getCurrentWeek(new Date());
},1000)
},
},
vue的工具类
export function getCurrentTime(time){ //获取几点几分
let date = new Date(time);
let hour = date.getHours() + '';
let minute = date.getMinutes() < 10 ? '0'+ date.getMinutes() : date.getMinutes();
return hour + ":" + minute;
}
export function getCurrentDate(d,time){ //获取几月几号或者几天后的日期
let date = new Date(time);
let month;
let day;
if(!day){
let newDate = date.setDate(date.getDate() + d);
newDate = new Date(newDate);
month = newDate.getMonth() + 1 < 10 ? '0'+ (newDate.getMonth() + 1 ) : newDate.getMonth() + 1;
day = newDate.getDate() < 10 ? '0'+ newDate.getDate() : newDate.getDate();
}
else{
month = date.getMonth() + 1 < 10 ? '0'+ (date.getMonth() + 1 ) : date.getMonth() + 1;
day = date.getDate() < 10 ? '0'+ date.getDate() : date.getDate();
}
return month + '/' + day;
}
export function getCurrentWeek(time){ //获取周几
let date = new Date(time);
let arr = new Array("日", "一", "二", "三", "四", "五", "六");
let weekday = '周' + arr[date.getDay()];
return weekday;
}
细心的小伙伴可能已经注意到了,关键就在于开启定时器和传入公共函数当前日期(new Date()),让更新的数据以现在的时间为基准;setInterval一秒钟查询一次,由于我们这里是响应式数据,数据有变化的话,会立即在页面上展示数据,就达到了我们所说的实时更新功能。