頁面掛載的時候定時器搞起
<el-row> <div class="ui-toolbar" style="height: 32px; line-height: 32px;"> <div style="margin-left:10px;" :class="isExecuteTiming ? 'green': 'red'">AUTO Refresh</div> <div style="margin-left:10px; margin-right:10px;"> <el-input v-model="autoRefreshInterval" style="width:50px;padding:0;text-align:center" @change="RefreshIntervalChange($event)"></el-input> </div> <div style="color: gray;">秒</div> <div style="margin-left:20px;cursor: pointer" @click="stopAutoRefreshTimer()" v-if="autoRefreshTimer !== null"> <img style="margin-top:10px;" src="@/assets/img/icon/ico_btn_stop.png" title="停止暫停自動刷新"/> </div> <div style="margin-left:20px;cursor: pointer" @click="startAutoRefreshTimer()" v-else> <img style="margin-top:10px;" src="@/assets/img/icon/ico_btn_start.png" title="啟動暫停自動刷新"/> </div> <div style="margin-left:10px;cursor: pointer" @click="refreshData(curTabKey)"> <img style="margin-top:10px;" src="@/assets/img/icon/ico_btn_refresh.png" title="手動刷新"/> </div> <div ref="countDownValue" style="margin-left:10px;font-size:15px;color:red;font-weight:bold;"> {{countDown}} </div> </div> </el-row>
export default class AgentActiveServiceList extends Vue { @Prop(Object) // 自動刷新的時間間隔(單位s) public autoRefreshInterval: number = 10;
// 定時器倒計時的值 public countDown!: number;
// 暫停時候賦值的變量 public stopValue!: number; /** * 生命周期:構造函數 */ public constructor() { super(); // 變量初始化this.countDown = this.autoRefreshInterval; }
}
/** * 生命周期:對象銷毀完前 */ public mounted () {this.stopAutoRefreshTimer();
} /** * 啟動定時刷新定時器 */ public startAutoRefreshTimer() {
//如果暫停過,就重新開啟定時器,並把暫停時取得值傳給定時器當初始值,沒暫停過就以頁面加載時的定時器初始值 if (this.stopValue) { this.countDownDate(this.stopValue); } else { this.countDownDate(this.autoRefreshInterval); } } // 倒計時顯示 public countDownDate(inputDate: any) {
// 如果之前開啟過,先關閉之前的再開啟新的 if (this.refreshInterval) { clearInterval(this.refreshInterval); }
// 把每次要開啟定時器的值賦值給定時器,讓他去自減 this.countDown = inputDate;
// 把定時器賦值給變量,方便日后關閉 this.refreshInterval = setInterval(() => { this.countDown--; if (this.countDown < 1) {
// 如果有暫停過的情況,賦過來的值就是暫停時的值,那么每次自減循環的是暫停是的值,而不是初始值,需要判斷
// 如果賦過來的的值 不等於 初始值,就把初始值賦給傳過來的值,還不明白的話試一把就知道了
inputDate !== this.autoRefreshInterval ? this.countDown = this.autoRefreshInterval : this.countDown = inputDate; } }, 1000); }
停止
/** * 停止自動刷新定時器 */ public stopAutoRefreshTimer() { //清除定時器 clearInterval(this.refreshInterval);
//暫停的值存起來 that.stopValue = that.$refs.countDownValue.innerText; }
繼續
/** * 啟動定時刷新定時器 */ public startAutoRefreshTimer() { //如果暫停過,就重新開啟定時器,並把暫停時取得值傳給定時器當初始值,沒暫停過就以頁面加載時的定時器初始值 if (this.stopValue) { this.countDownDate(this.stopValue); } else { this.countDownDate(this.autoRefreshInterval); } }
刷新
/** * 刷新數據 */ public refreshData() { //賦初值開啟定時器即可this.countDownDate(this.autoRefreshInterval); }