今天在改东西,写了一个实现系统时间的功能,效果是下面这样子的:
由于代码都有详细的注释,所以请直接看代码
<template>
<div id="index">
<div class="">
尊敬的管理员,下午好!当前时间: {{dateTime}}
</div>
</div>
</template>
<script>
export default {
name: 'index',
data() {
return {
dateTime:'',//要显示的时间
nowTime:new Date(),//获取到的时间
haoMiao:false//毫秒
}
},
methods:{
// 设置年月日时分秒
getTime(){
var str='';
this.nowTime = this.haoMiao?(new Date(this.haoMiao)):this.nowTime//把毫秒转成日期格式
str += this.nowTime.getFullYear()+'/';//获取年份
str += this.setZero(this.nowTime.getMonth()+1,'/','1');//获取月份
str += this.setZero(this.nowTime.getDate(),' ');//获取日
str += this.setZero(this.nowTime.getHours(),':');//获取时
str += this.setZero(this.nowTime.getMinutes(),':');//获取分
str += this.setZero(this.nowTime.getSeconds(),'');//获取秒
this.dateTime = str;
this.haoMiao = this.haoMiao?this.haoMiao:(new Date(this.nowTime).getTime())//把日期格式转成毫秒
this.haoMiao += 1000//每次执行增加1秒
},
// 小于10的数字在前面加0
setZero(a,b){
var str = '';
str = a<10?('0'+a):a
str += b
return str
}
},
mounted(){
this._cache_timeout_id_ = setInterval(this.getTime,1000);//组件挂载的完毕执行定时器
},
created(){
this.getTime()//组件加载执行一次,因为setInterval定时器要1秒后才执行
},
destroyed(){
window.clearInterval(this._cache_timeout_id_)//组件销毁时候停止定时器,不然会一直执行下去
}
}
</script>