1.在vue页面定义一个div放置时间:
<div> <h3 v-model="date" id="timeStyle">当前日期:{{date | formatDate}}</h3> </div>
2.在mounted中定义定时器和定时器的销毁方法
mounted() { let _this = this; // 声明一个变量指向Vue实例this,保证作用域一致 this.timer = setInterval(() => { _this.date = new Date(); // 修改数据date }, 1000) }, beforeDestroy() { if (this.timer) { clearInterval(this.timer); // 在Vue实例销毁前,清除我们的定时器 } }, beforeDestroy: function () { if (this.timer) { clearInterval(this.timer); } },
3.定义一个时间格式化的过滤器
var padDate = function (value) {
return value <10 ? '0' + value:value;
};
//时间过滤器 filters: { formatDate:function (value) { var date = new Date(value); var year = date.getFullYear(); var month = padDate(date.getMonth()+1); var day = padDate(date.getDate()); var hours = padDate(date.getHours()); var minutes = padDate(date.getMinutes()); var seconds = padDate(date.getSeconds()); //var week = padDate(date.getDay()); let week = new Date(value).getDay(); let weeks = ["日","一","二","三","四","五","六"]; let getWeek = "星期" + weeks[week]; //return year + '-' + month + '-' + day +' '+'|' + ' ' + hours + ':' + minutes + ':' + seconds + ' ' +getWeek; return year + '-' + month + '-' + day +' '+'|'+' ' +getWeek; } },
4.在style中定义时间显示的格式
#timeStyle{ color: #bcdcff; right: 180px; top: 20px; font-size: 16px; position: absolute; }
5.时间显示效果