一、引入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 }
這樣就可以實現時間實時更新啦