一:在data中定义一个字符串,用于保存时间:nowTime
二:在methods钩子函数中定义三个函数(注意:"星期"+'日一二三四五六'.charAt(new Date().getDay()) 这段代码用来获取具体的星期几)
timeFormate(timeStamp) { let year = new Date(timeStamp).getFullYear(); let month =new Date(timeStamp).getMonth() + 1 < 10? "0" + (new Date(timeStamp).getMonth() + 1): new Date(timeStamp).getMonth() + 1; let date =new Date(timeStamp).getDate() < 10? "0" + new Date(timeStamp).getDate(): new Date(timeStamp).getDate(); let hh =new Date(timeStamp).getHours() < 10? "0" + new Date(timeStamp).getHours(): new Date(timeStamp).getHours(); let mm =new Date(timeStamp).getMinutes() < 10? "0" + new Date(timeStamp).getMinutes(): new Date(timeStamp).getMinutes(); let ss =new Date(timeStamp).getSeconds() < 10? "0" + new Date(timeStamp).getSeconds(): new Date(timeStamp).getSeconds(); this.nowTime = year + "." + month + "." + date +" "+"星期"+'日一二三四五六'.charAt(new Date().getDay())+" "+hh+":"+mm+':'+ss ; }, nowTimes(){ this.timeFormate(new Date()); setInterval(this.nowTimes,1000); this.clear() }, clear(){ clearInterval(this.nowTimes) this.nowTimes = null; }
三:在mounted钩子函数中调用nowTimes函数、在beforeDestroy钩子函数中调用clear函数
mounted() { this.nowTimes(); }, beforeDestroy() { this.clear(); }
四:最后,显示在界面上
<div class="head_date">{{nowTime}}</div>
借鉴地址:https://blog.csdn.net/qq_42647749/article/details/100741957