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);
}
},
上文中的$moment为整理时间格式的插件。
引用moment插件
npm i moment --save
//main.js
import moment from 'moment'
Vue.prototype.$moment = moment;