vue项目中,添加一个自动跳动的时间模块
许多项目中在首页或者头部模块,会放置一个当前时间,并且是动态的,现在把这个小模块进行一个记录。
页面元素模块:
<div class="now-time-box">
<p class="now-time">{{loopTime}}</p>
<span class="now-week">{{loopWeek}}</span>
<span class="now-date">{{loopDate}}</span>
</div>
分别代表 时分秒、星期几、年月日
methods里面的方法:
propTime() {
// eslint-disable-next-line no-extend-native
Date.prototype.format = function(fmt) {
var o = {
'M+': this.getMonth() + 1,
'd+': this.getDate(),
'H+': this.getHours(),
'm+': this.getMinutes(),
's+': this.getSeconds(),
'q+': Math.floor((this.getMonth() + 3) / 3),
S: this.getMilliseconds() // 毫秒
};
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(
RegExp.$1,
(this.getFullYear() + '').substr(4 - RegExp.$1.length)
);
}
for (var k in o) {
if (new RegExp('(' + k + ')').test(fmt)) {
fmt = fmt.replace(
RegExp.$1,
RegExp.$1.length == 1
? o[k]
: ('00' + o[k]).substr(('' + o[k]).length)
);
}
}
return fmt;
};
},
loop() {
setInterval(this.computeTime, 1000);
},
computeTime() {
const weeks = [
'星期天',
'星期一',
'星期二',
'星期三',
'星期四',
'星期五',
'星期六'
];
const now = new Date();
this.loopTime = now.format('HH:mm:ss');
this.loopDate = now.format('yyyy/MM/dd');
this.loopWeek = weeks[now.getDay()];
}
然后在mounted里面进行调用即可
mounted() {
this.propTime();
this.loop();
this.computeTime();
}
浙公网安备 33010602011771号