data() {
return {
timer: "",
dateTime: this.getCurrentTime(),//当前时间
}
},
created() {
//定时器:当前时间
this.timer = setInterval(() => {
this.dateTime = this.getCurrentTime();
}, 1000);
},
methods: {
//获取当前时间
getCurrentTime() {
return this.$moment(new Date()).format('YYYY/MM/DD HH:mm:ss');
}
},
beforeDestroy() {
//在vue实例销毁前,清除定时器
if (this.timer) {
clearInterval(this.timer);
}
},
The $moment above is a plug-in to organize the time format.
Reference moment plugin
npm i moment --save
//main.js
import moment from 'moment'
Vue.prototype.$moment = moment;