问题: 下拉加载的时候,会多次触发并调用getLiveData,由于该函数共享一个currentPage变量,导致数据不安全问题
错误代码:
const getLiveData = async () => {
if(currentPage.value >= totalPage.value) return false
const res = await requestLiveData(currentPage.value + 1)
currentPage.value = currentPage.value + 1
liveData.value.push(...res.list)
console.log(res.list)
return true
}
错误原因分析:由于vue是非阻塞的,当第一次调用到const res = await requestLiveData(currentPage.value + 1) 这一步的时候,需要去请求网络,res变量会等待获得响应资源,又由于是非阻塞的,下一个异步请求会执行,而这个时候currentPage.value还没有更新,即这次请求的参数其实是错误的,将会导致数据错误。
解决:
添加一个锁变量isFetching
const getLiveData = async () => {
if(isFetching) return true
if(currentPage.value >= totalPage.value) return false
isFetching = true;
try{
const res = await requestLiveData(currentPage.value + 1)
currentPage.value = currentPage.value + 1
liveData.value.push(...res.list)
console.log(res.list)
return true
}finally{
isFetching = false;
}
}