今天在做vue项目中想让我的页面显示一下当前时间,就有了一下的解决方法,亲测有效,还不赶紧试试。

1.需要在data中定义一个当前时间的字符串

data(){
    return{
      nowTime: ''
    }
  },

2.在methods中定义三个方法

  //获取当前时间
    timeNow(timeStamp) {
      let year = new Date(timeStamp).getFullYear();
      let month =new Date(timeStamp).getMonth() + 1 < 10? "0" + (new Date(timeStamp).getMonth() + 1): new Date(timeStamp).getMonth() + 1;
      let date =new Date(timeStamp).getDate() < 10? "0" + new Date(timeStamp).getDate(): new Date(timeStamp).getDate();
      let hh =new Date(timeStamp).getHours() < 10? "0" + new Date(timeStamp).getHours(): new Date(timeStamp).getHours();
      let mm =new Date(timeStamp).getMinutes() < 10? "0" + new Date(timeStamp).getMinutes(): new Date(timeStamp).getMinutes();
      let ss =new Date(timeStamp).getSeconds() < 10? "0" + new Date(timeStamp).getSeconds(): new Date(timeStamp).getSeconds();
      this.nowTime = year + "年" + month + "月" + date +"日  "+"星期"+'日一二三四五六'.charAt(new Date().getDay())+" "+hh+":"+mm+':'+ss ;
    },
    // 实时刷新当前时间,格式化
    nowTimes(){
      this.timeNow(new Date());
      setInterval(this.nowTimes,1000);
      this.clear()
    },
    //清除定时器
    clear(){
      clearInterval(this.nowTimes)
      this.nowTimes = null;
    }

3.在mounted钩子函数中调用nowTimes函数、在beforeDestroy钩子函数中调用clear函数

//在mounted钩子函数中调用nowTimes函数、在beforeDestroy钩子函数中调用clear函数
  mounted () {
    this.nowTimes()
  },
  beforeDestroy () {
    this.clear()
  }

4.在vue中引用刚刚定义的字符串

5.效果

这样就大功告成了

 

 

GitHub 加速计划 / vu / vue
207.52 K
33.66 K
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:1 个月前 )
73486cb5 * chore: fix link broken Signed-off-by: snoppy <michaleli@foxmail.com> * Update packages/template-compiler/README.md [skip ci] --------- Signed-off-by: snoppy <michaleli@foxmail.com> Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 3 个月前
e428d891 Updated Browser Compatibility reference. The previous currently returns HTTP 404. 3 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐