vue实现loading组件
Vue 实现 Loading 组件的方法
基础实现方案
创建一个独立的 Loading.vue 组件文件:
<template>
<div v-if="isLoading" class="loading-overlay">
<div class="loading-spinner"></div>
</div>
</template>
<script>
export default {
props: {
isLoading: {
type: Boolean,
default: false
}
}
}
</script>
<style>
.loading-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
z-index: 9999;
}
.loading-spinner {
border: 4px solid #f3f3f3;
border-top: 4px solid #3498db;
border-radius: 50%;
width: 40px;
height: 40px;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
全局注册方案
在 main.js 中全局注册并使用:

import Vue from 'vue'
import Loading from './components/Loading.vue'
Vue.component('Loading', Loading)
// 或者作为插件使用
const LoadingPlugin = {
install(Vue) {
Vue.prototype.$loading = {
show() {
// 显示逻辑
},
hide() {
// 隐藏逻辑
}
}
}
}
Vue.use(LoadingPlugin)
使用 Vuex 管理状态
// store.js
export default new Vuex.Store({
state: {
isLoading: false
},
mutations: {
setLoading(state, payload) {
state.isLoading = payload
}
}
})
// 组件中使用
<template>
<Loading :isLoading="$store.state.isLoading" />
</template>
高级实现方案
使用动态导入和异步组件:

// 创建一个高阶组件
const asyncComponent = (componentImport) => {
const AsyncComponent = () => ({
component: componentImport,
loading: LoadingComponent,
delay: 200,
timeout: 3000
})
return AsyncComponent
}
请求拦截方案
在 axios 拦截器中控制 loading 状态:
let loadingCount = 0
axios.interceptors.request.use(config => {
loadingCount++
store.commit('setLoading', true)
return config
})
axios.interceptors.response.use(response => {
loadingCount--
if (loadingCount <= 0) {
store.commit('setLoading', false)
}
return response
}, error => {
loadingCount--
if (loadingCount <= 0) {
store.commit('setLoading', false)
}
return Promise.reject(error)
})
第三方库方案
使用现成的 loading 库:
npm install vue-loading-overlay
import Loading from 'vue-loading-overlay'
import 'vue-loading-overlay/dist/vue-loading.css'
Vue.use(Loading)
每种实现方案都有其适用场景,可以根据项目需求选择合适的实现方式。基础方案适合简单场景,全局方案适合大型应用,Vuex 方案适合状态管理复杂的项目,拦截器方案适合需要自动控制 loading 状态的场景。






