個人筆記006--vue利用定時器實現系統時間

今天在改東西,寫了一個實現系統時間的功能,效果是下面這樣子的:

由於代碼都有詳細的註釋,所以請直接看代碼

<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>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章