vue moment.js及实时更新当前时间

一、引入moment

1.安装 cnpm install moment --save

2.import引入 import moment from 'moment'

3.设置moment区域为中国,引入:

import 'moment/locale/zh-cn'

moment.locale('zh-cn')

二、获取当前时间

 1 <div>{{nowtime | updatetime}}</div>
 2 <script>
 3     export default{
 4         data(){
 5             return{
 6                 nowtime:new Date()
 7             }
 8         },
 9         filters:{
10             updatetime:function(value){
11                 return moment(value).format('LTS');
12             }
13         }
14     }
15 </script>    

其中moment().format('LTS')获取时间格式为:10:15:23类型

三、让时间实时更新

让时间实时更新用计时器,代码如下

 1 mounted(){//生命周期模板挂载之后
 2     let _this=this;
 3     this.timer=setInterval(()=>{
 4         _this.nowtime=new Date();
 5     },1000)
 6 },
 7 beforeDestroy(){//生命周期实例销毁之前
 8     if(this.timer){
 9         clearInterval(this.timer);
10     }
11 }  

这样就可以实现时间实时更新啦