代碼:
export default{
data(){
return{
date:new Date()
}
},
methods:{
dateFormat(time) {
var date=new Date(time);
var year=date.getFullYear();
/* 在日期格式中,月份是從0開始的,因此要加0
* 使用三元表達式在小於10的前面加0,以達到格式統一 如 09:11:05
* */
var month= date.getMonth()+1<10 ? "0"+(date.getMonth()+1) : date.getMonth()+1;
var day=date.getDate()<10 ? "0"+date.getDate() : date.getDate();
var hours=date.getHours()<10 ? "0"+date.getHours() : date.getHours();
var minutes=date.getMinutes()<10 ? "0"+date.getMinutes() : date.getMinutes();
var seconds=date.getSeconds()<10 ? "0"+date.getSeconds() : date.getSeconds();
// 拼接
return year+"-"+month+"-"+day+" "+hours+":"+minutes+":"+seconds;
}
},
mounted() {
//顯示當前日期時間
let _this = this// 聲明一個變量指向Vue實例this,保證作用域一致
this.timer = setInterval(() => {
_this.date = new Date(); // 修改數據date
}, 1000)
},
beforeDestroy() {
if (this.timer) {
clearInterval(this.timer); // 在Vue實例銷燬前,清除我們的定時器
}
}
使用:
<div>{{dateFormat(date)}}</div>
效果圖: