vue+elementui表格異步加載數據導致字段缺失的解決方案
在使用Vue和ElementUI構建應用時,異步數據加載常常會導致視圖更新與數據加載時機不匹配,從而出現字段缺失等問題。本文將分析一個實際案例,并提供有效的解決方案。
問題描述: 一個使用el-table組件顯示申請記錄的應用,數據需要通過多個異步請求獲取。初始加載時,申請人姓名等關鍵字段缺失,只有在打開瀏覽器開發者工具(F12)后才顯示。根本原因在于異步請求完成的時機與el-table渲染的時機不一致。
以下是一個存在問題的代碼片段:
立即學習“前端免費學習筆記(深入)”;
async getdata() { await axios.get("http://localhost:10100/apply/getalloutapplypageofgroup", { // ...請求參數... }).then(res => { this.tabledata = res.data.data.records; this.total = res.data.data.total; }); for (let i = 0; i < this.tabledata.length; i++) { await axios.get("http://localhost:10100/user/getusername", { params: { userid: this.tabledata[i].applicantid } }).then(res => { this.tabledata[i].applicantname = res.data.data; }); // ... 其他異步請求 ... } }
getdata函數在mounted生命周期中調用。雖然使用了await,但它只等待每個單個請求完成,并非所有請求都完成后再更新視圖。 this.tabledata賦值給el-table時,后續請求仍在進行,導致字段缺失。開發者工具的打開可能觸發了頁面重新渲染,從而顯示完整數據。
解決方案:使用promise.all
為了確保所有異步請求完成后再更新視圖,應將所有異步操作放在Promise.all中。修改后的代碼如下:
async getData() { await axios.get("http://localhost:10100/Apply/getAllOutApplyPageOfGroup", { // ...請求參數... }).then(res => { this.tableData = res.data.data.records; this.total = res.data.data.total; const promises = this.tableData.map(item => Promise.all([ axios.get("http://localhost:10100/User/getUserName", { params: { userId: item.applicantId } }), axios.get("http://localhost:10100/Chemicals/getChemicalName", { params: { chemicalId: item.chemicalId } }), axios.get("http://localhost:10100/Chemicals/getUnit", { params: { chemicalId: item.chemicalId } }) ])); Promise.all(promises).then(results => { results.forEach((result, index) => { this.tableData[index].applicantName = result[0].data.data; this.tableData[index].chemicalName = result[1].data.data; this.tableData[index].unit = result[2].data.data; // ... 其他字段處理 ... }); }); }); }
Promise.all確保所有請求完成后再更新this.tableData,從而解決數據顯示不完整的問題,保證頁面初始加載時顯示所有字段。 這避免了異步操作與視圖更新的時機沖突。
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END
喜歡就支持一下吧
相關推薦