需求:每隔一段時間獲取最新數據,然后渲染到頁面。如下圖效果。
思路:使用定時器,每隔一段時間發起一次請求。
代碼:
data() {
return {
// 定時器
timer: null,
// 展示的數據
info: []
}
},
methods: {
getInfo() {
// 輪詢獲取更新過程中的信息
let num = 1
if (this.timer) {
clearInterval(this.timer)
} else {
this.timer = setInterval(() => {
// 在這里發送請求獲取數據
this.updateInfo.push('升級的第'+ num++ +'步')
if (num === 3) {
clearInterval(this.timer)
this.timer = null
}
}, 1500);
}
}
}
清理定時器的時機:
- 通常情況下,我們可以在
destroyed
鈎子函數中清除定時器 - 但有些時候,比如在 dialog 彈出框中就無法使用
destroyed
鈎子清除,可以根據代碼邏輯在合適的地方清除定時器。
// 清除定時器的代碼
clear() {
clearInterval(this.timer)
this.timer = null
}
滾動條顯示在底部---展示最新的內容
當輪詢的數據過多出現滾動條的時候,我們希望滾動條顯示在最底部,也就是展示最新的信息。
思路:利用 JS 中的 scrollTop = scrollHeight
來實現
scrollHeight
:包括overflow
樣式屬性導致的視圖中不可見內容,沒有垂直滾動條的情況下,scrollHeight
值與元素視圖填充所有內容所需要的最小值clientHeight
相同。包括元素的padding
,但不包括元素的margin
。scrollTop
:可以設置或者獲取一個元素距離他容器頂部的像素距離。一個元素的scrollTop
是可以去計算出這個元素距離它容器頂部的可見高度。當一個元素的容器沒有產生垂直方向的滾動條,那它的scrollTop
的值默認為0。
實現代碼:
添加下面的代碼到定時器中
this.$nextTick(() => {
let info = this.$refs.updateInfoRef
info.scrollTop = info.scrollHeight
})
參考文章:https://blog.csdn.net/weixin_38858002/article/details/82114774
https://blog.csdn.net/weixin_41190571/article/details/86509383