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

Vue技术需求:HTTP请求进行时显示加载器,完成后隐藏

嘿,这个需求在Vue里实现起来挺顺手的,我给你两种常用的方案,你可以根据项目场景来选~

方案1:单个请求的局部加载控制

如果只是针对某一个特定请求需要显示加载器,直接用组件内的响应式变量就能搞定,逻辑简单直观:

<script setup>
import { ref } from 'vue'
// 用响应式变量控制加载器的显示隐藏
const isLoading = ref(false)

// 模拟实际HTTP请求的函数,你可以替换成axios/fetch的真实请求
async function fetchData() {
  // 请求开始前,打开加载器
  isLoading.value = true
  try {
    // 这里替换成你的实际请求逻辑,比如 await axios.get('/api/your-data')
    const response = await new Promise(resolve => setTimeout(() => resolve('请求成功'), 1500))
    console.log('请求结果:', response)
    // 这里写请求成功后的业务逻辑,比如更新页面数据
  } catch (error) {
    console.error('请求出错:', error)
    // 请求失败的处理,比如提示用户
  } finally {
    // 不管请求成功还是失败,最终都要关闭加载器
    isLoading.value = false
  }
}
</script>

<template>
  <div class="request-container">
    <!-- 加载器:只有isLoading为true时显示 -->
    <div v-if="isLoading" class="loader">正在加载,请稍候...</div>
    <!-- 触发请求的按钮,加载时禁用防止重复点击 -->
    <button @click="fetchData" :disabled="isLoading">发起请求</button>
    <!-- 页面其他内容 -->
  </div>
</template>

<style scoped>
.loader {
  padding: 1rem;
  background-color: #f8f9fa;
  border-radius: 4px;
  margin-bottom: 1rem;
  color: #495057;
}
button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>

这里核心是用try...finally块,确保无论请求成功还是失败,加载器都会被隐藏,不会出现一直卡在加载状态的情况。

方案2:全局请求拦截器实现全局加载控制

如果你的项目里有很多请求,想要统一显示全局加载器(比如全屏加载罩、顶部进度条),用HTTP请求拦截器会更高效,不用在每个请求里重复写加载逻辑:

步骤1:创建全局加载状态管理(用Pinia举例)

我们需要一个全局状态来追踪请求的数量,避免多个并发请求时,一个请求结束就关闭加载器的问题:

// stores/loading.js
import { defineStore } from 'pinia'

export const useLoadingStore = defineStore('loading', {
  state: () => ({
    isLoading: false,
    // 统计当前活跃的请求数量
    activeRequests: 0
  }),
  actions: {
    startLoading() {
      this.activeRequests++
      this.isLoading = true
    },
    endLoading() {
      this.activeRequests--
      // 只有当所有请求都完成时,才关闭加载器
      if (this.activeRequests <= 0) {
        this.isLoading = false
        this.activeRequests = 0 // 重置计数,避免出现负数
      }
    }
  }
})

步骤2:配置Axios拦截器

假设你用Axios做HTTP请求,给它添加请求和响应拦截器,自动更新加载状态:

// utils/axios.js
import axios from 'axios'
import { useLoadingStore } from '@/stores/loading'

// 创建Axios实例
const axiosInstance = axios.create({
  baseURL: '/api' // 替换成你的API地址
})

// 请求拦截器:发起请求时开启加载
axiosInstance.interceptors.request.use(
  config => {
    const loadingStore = useLoadingStore()
    loadingStore.startLoading()
    return config
  },
  error => {
    const loadingStore = useLoadingStore()
    loadingStore.endLoading()
    return Promise.reject(error)
  }
)

// 响应拦截器:请求完成(成功/失败)时关闭加载
axiosInstance.interceptors.response.use(
  response => {
    const loadingStore = useLoadingStore()
    loadingStore.endLoading()
    return response
  },
  error => {
    const loadingStore = useLoadingStore()
    loadingStore.endLoading()
    return Promise.reject(error)
  }
)

export default axiosInstance

步骤3:在根组件中使用全局加载器

在App.vue里引入全局加载状态,渲染全局加载罩:

<!-- App.vue -->
<script setup>
import { useLoadingStore } from '@/stores/loading'
const loadingStore = useLoadingStore()
</script>

<template>
  <div id="app">
    <!-- 全局加载罩:覆盖整个页面 -->
    <div v-if="loadingStore.isLoading" class="global-loader">
      <div class="spinner">加载中...</div>
    </div>
    <!-- 页面路由内容 -->
    <router-view />
  </div>
</template>

<style scoped>
.global-loader {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(255, 255, 255, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}
.spinner {
  font-size: 1.5rem;
  color: #212529;
  /* 可以加个CSS旋转动画让加载更直观 */
  animation: spin 1s linear infinite;
}
@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>

额外小提示

  • 如果不用Pinia,也可以用Vue的provide/inject传递全局加载状态,或者直接用一个全局响应式对象(比如const loadingState = ref({ isLoading: false, activeRequests: 0 }))。
  • 加载器的样式可以完全自定义,也可以直接用UI组件库的现成加载组件(比如Element Plus的ElLoading、Ant Design Vue的a-spin),省得自己写CSS动画。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:13:56