vue数据请求接口数据量太大如何判断数据是否加载完成

vue yekong 65℃

vue数据可视化大屏项目开发中,客户接口返回的数据量太大,一次请求大概几十兆的样子,所以需要判断数据是否加载完成了。

这里我们可以通过axios的finally来判断数据是否加载完成了。

我们在请求数据前设置一个状态标识,用来确认是否显示加载中的图标。

this.isLoading = true; // 开始加载数据,显示加载动画

try {
response = await axios.post(url, data, {
  headers: {
    'Content-Type': 'application/xml', // 根据服务器要求设置适当的Content-Type
  },
});
// 处理响应数据
this.addGeoJsonToMap(response.data);
// 渲染完成后,清除原始GeoJSON数据
response = null;
riverCodes = null;
filterConditions = null;
} catch (error) {
console.error('请求失败:', error);
// 处理错误
} finally {
this.isLoading = false; // 完成加载,隐藏加载动画
}try {
response = await axios.post(url, data, {
  headers: {
    'Content-Type': 'application/xml', // 根据服务器要求设置适当的Content-Type
  },
});
// 处理响应数据
this.addGeoJsonToMap(response.data);
// 渲染完成后,清除原始GeoJSON数据
response = null;
riverCodes = null;
filterConditions = null;
} catch (error) {
console.error('请求失败:', error);
// 处理错误
} finally {
this.isLoading = false; // 完成加载,隐藏加载动画
}

在使用 Axios 进行 API 请求时,finally 方法是一个在请求结束后(无论成功或失败)都会执行的处理器。这使得它成为处理加载状态的理想选择,特别是在需要清理或执行一些最终步骤的情况下。

原理解释

当你发起一个 Axios 请求,如使用 axios.get()axios.post() 等方法,你可以链式调用 .then().catch().finally() 方法。其中:

  • .then() 用于处理请求成功的情况。
  • .catch() 用于处理请求失败的情况。
  • .finally() 用于执行那些无论请求成功还是失败都需要执行的代码。

在实际应用中,finally 常用于停止显示加载指示器(如旋转的加载图标),因为无论请求成功还是失败,用户都应该知道请求已经完成,界面可以进行下一步操作。

示例代码

this.isLoading = true; // 开始显示加载指示器

axios.get('https://api.wanjunshijie.com/data')
  .then(response => {
    // 处理成功的响应
    console.log('Data fetched successfully:', response.data);
  })
  .catch(error => {
    // 处理错误
    console.error('Failed to fetch data:', error);
  })
  .finally(() => {
    this.isLoading = false; // 关闭加载指示器
  });

在这个例子中,无论数据请求成功 (then) 还是失败 (catch),finally 都会执行,确保 isLoading 状态被设置为 false,从而停止显示加载指示器。

结论

使用 finally 方法可以有效地确保在数据请求完成后执行必要的清理工作,如隐藏加载动画,这对于提升用户体验非常关键。这种模式确保了代码的整洁和效率,同时减少了重复代码的需要,因为你不需要在 thencatch 每个块中都写上停止加载的代码。

喜欢 (0)