当前位置:首页 > VUE

vue axios实现loading

2026-02-19 06:54:49VUE

使用 Axios 拦截器实现全局 Loading

在 Vue 项目中,可以通过 Axios 的请求拦截器和响应拦截器实现全局 Loading 效果。以下是一个完整的实现方案:

安装 Axios(如果未安装):

npm install axios

在 Vue 项目中创建 Axios 实例并配置拦截器:

vue axios实现loading

// src/utils/request.js
import axios from 'axios'
import { ElLoading } from 'element-plus' // 以 Element Plus 为例

const service = axios.create({
  baseURL: '/api',
  timeout: 5000
})

let loadingInstance

service.interceptors.request.use(config => {
  loadingInstance = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  return config
}, error => {
  loadingInstance.close()
  return Promise.reject(error)
})

service.interceptors.response.use(response => {
  loadingInstance.close()
  return response.data
}, error => {
  loadingInstance.close()
  return Promise.reject(error)
})

export default service

在组件中使用封装好的 Axios 实例

import request from '@/utils/request'

export default {
  methods: {
    fetchData() {
      request.get('/user/list')
        .then(data => {
          console.log(data)
        })
        .catch(error => {
          console.error(error)
        })
    }
  }
}

自定义 Loading 组件实现

如果需要使用自定义 Loading 组件而非 UI 库的 Loading:

// src/components/CustomLoading.vue
<template>
  <div v-if="visible" class="loading-overlay">
    <div class="loading-spinner"></div>
    <div class="loading-text">{{ text }}</div>
  </div>
</template>

<script>
export default {
  props: {
    visible: Boolean,
    text: {
      type: String,
      default: 'Loading...'
    }
  }
}
</script>

<style>
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}
</style>

在 Axios 拦截器中使用自定义 Loading:

vue axios实现loading

import Vue from 'vue'

let loadingCount = 0
let loadingComponent

function showLoading() {
  if (loadingCount === 0) {
    const LoadingConstructor = Vue.extend(CustomLoading)
    loadingComponent = new LoadingConstructor({
      propsData: { visible: true }
    })
    loadingComponent.$mount()
    document.body.appendChild(loadingComponent.$el)
  }
  loadingCount++
}

function hideLoading() {
  loadingCount--
  if (loadingCount <= 0) {
    loadingComponent.$el.remove()
    loadingComponent.$destroy()
    loadingComponent = null
    loadingCount = 0
  }
}

service.interceptors.request.use(config => {
  showLoading()
  return config
})

service.interceptors.response.use(response => {
  hideLoading()
  return response
}, error => {
  hideLoading()
  return Promise.reject(error)
})

按需启用 Loading 的功能

某些请求可能需要禁用 Loading,可以通过自定义配置实现:

service.interceptors.request.use(config => {
  if (config.showLoading !== false) {
    showLoading()
  }
  return config
})

// 使用时不显示 Loading
request.get('/user/info', { showLoading: false })

防止快速请求导致的 Loading 闪烁

添加延时隐藏逻辑,避免 Loading 频繁闪烁:

let hideLoadingTimer

function hideLoading() {
  hideLoadingTimer = setTimeout(() => {
    if (loadingCount <= 0 && loadingComponent) {
      clearTimeout(hideLoadingTimer)
      loadingComponent.$el.remove()
      loadingComponent.$destroy()
      loadingComponent = null
    }
  }, 300) // 延迟 300ms 隐藏
}

标签: vueaxios
分享给朋友:

相关文章

vue实现星星

vue实现星星

实现星星评分的Vue组件 使用Vue实现星星评分功能可以通过组件化方式完成,以下是一个完整的实现方案: 模板部分 <template> <div class="star-ra…

vue权限实现

vue权限实现

Vue 权限实现方案 基于路由的权限控制 通过路由守卫实现权限验证,在路由配置中添加meta字段标记权限要求。在router.beforeEach中检查用户权限与路由要求的匹配情况。 // rout…

vue首页实现

vue首页实现

实现Vue首页的基本步骤 创建一个Vue首页通常涉及项目初始化、页面结构设计、路由配置和组件开发。以下是具体实现方法: 初始化Vue项目 使用Vue CLI或Vite快速搭建项目结构: npm i…

vue实现注册

vue实现注册

Vue 实现注册功能 注册功能通常涉及前端表单、数据验证、与后端 API 的交互等步骤。以下是一个完整的 Vue 实现注册功能的方案。 创建注册表单 使用 Vue 的模板语法创建注册表单,包含用户名…

vue nexttrick实现

vue nexttrick实现

Vue 中 nextTick 的实现原理 nextTick 是 Vue 提供的一个异步方法,用于在下次 DOM 更新循环结束之后执行延迟回调。它利用了 JavaScript 的事件循环机制,确保回调在…

vue实现eventbus

vue实现eventbus

Vue 中实现 EventBus 在 Vue 中,EventBus 是一种跨组件通信的机制,尤其适用于非父子组件之间的数据传递。以下是实现 EventBus 的几种方法: 方法一:使用 Vue 实例…