You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue 2异步组件网络错误捕获与错误信息展示方案咨询

Vue v2异步组件网络错误处理方案

要实现API调用出错时展示错误提示,你需要通过状态变量管理加载、成功、错误三种状态,对应渲染不同内容。具体实现步骤如下:

1. 新增状态管理变量

在组件的data中定义两个状态变量,分别控制加载状态和错误状态:

data() {
  return {
    showChild: false,
    isLoading: false,
    hasError: false
  }
}

2. 调整API调用逻辑

在mounted钩子中更新状态:请求开始时标记加载状态,成功后关闭加载并显示子组件,失败时标记错误状态并关闭加载:

mounted() {
  this.isLoading = true;
  fetch("https://api.github.com/users/dasdasdasdasdasdas") // 测试用错误URL
    .then(res => {
      // fetch仅在网络错误时触发catch,HTTP错误(如404)需手动判断
      if (!res.ok) {
        throw new Error('请求失败');
      }
      return res.json();
    })
    .then(data => {
      console.log(data);
      this.isLoading = false;
      this.showChild = true;
    })
    .catch(err => {
      console.log(err);
      this.isLoading = false;
      this.hasError = true;
    });
}

3. 更新模板渲染逻辑

根据状态变量依次渲染加载提示、错误提示和子组件:

<template>
  <div>
    <!-- 加载状态 -->
    <div v-if="isLoading">{{ loadingMessage }}</div>
    <!-- 错误状态 -->
    <div v-else-if="hasError">{{ errorMessage }}</div>
    <!-- 成功状态,展示子组件 -->
    <child-component
      v-else
      message="I am the child component."
      loadingMessage="Looking for child component..."
      errorMessage="Child component not available."
    ></child-component>
  </div>
</template>

这样就能在API请求的不同阶段展示对应内容:请求中显示加载提示,失败时显示错误提示,成功则渲染子组件。

内容的提问来源于stack exchange,提问作者fox

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 07:05:34