vue实现时间实时更新

这篇博客分享了在Vue项目中如何实现实时显示当前时间、日期和未来三天天气预报,通过设置定时器和利用Vue的响应式特性,达到数据实时更新的效果。代码示例展示了如何在模板和脚本部分操作,确保时间信息每秒更新并显示在页面上。
摘要由CSDN通过智能技术生成

这两天在写地图项目,有一个需求为实时显示现在的时间,原来我写的代码有一点问题就是刷新了时间才会更新,而不是实时更新,在网上查阅了一些博客,感觉部分同学写的不是很对,于是便有了这篇博客
先来看效果图:
在这里插入图片描述
下面展示具体的代码:
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一秒钟查询一次,由于我们这里是响应式数据,数据有变化的话,会立即在页面上展示数据,就达到了我们所说的实时更新功能。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值