vue实现全局loading
使用Vue插件实现全局Loading
在Vue项目中创建一个自定义插件,通过插件机制实现全局Loading功能。
// loading-plugin.js
const LoadingPlugin = {
install(Vue) {
const LoadingComponent = Vue.extend({
template: `
<div v-if="show" class="global-loading">
<div class="loading-spinner"></div>
<div class="loading-text">{{ text }}</div>
</div>
`,
data() {
return {
show: false,
text: '加载中...'
}
}
})
const loadingInstance = new LoadingComponent({
el: document.createElement('div')
})
document.body.appendChild(loadingInstance.$el)
Vue.prototype.$loading = {
show(text) {
loadingInstance.text = text || '加载中...'
loadingInstance.show = true
},
hide() {
loadingInstance.show = false
}
}
}
}
export default LoadingPlugin
在main.js中注册插件:
import Vue from 'vue'
import LoadingPlugin from './loading-plugin'
Vue.use(LoadingPlugin)
使用Vuex管理Loading状态
通过Vuex集中管理全局Loading状态,便于跨组件控制。

// store.js
export default new Vuex.Store({
state: {
loading: false,
loadingText: '加载中...'
},
mutations: {
SHOW_LOADING(state, text) {
state.loading = true
state.loadingText = text || '加载中...'
},
HIDE_LOADING(state) {
state.loading = false
}
}
})
创建全局Loading组件:
// GlobalLoading.vue
<template>
<div v-if="$store.state.loading" class="global-loading">
<div class="loading-spinner"></div>
<div class="loading-text">{{ $store.state.loadingText }}</div>
</div>
</template>
<script>
export default {
name: 'GlobalLoading'
}
</script>
在App.vue中引入:

<template>
<div id="app">
<GlobalLoading />
<router-view />
</div>
</template>
使用axios拦截器实现请求Loading
结合axios拦截器自动显示和隐藏Loading状态。
// http.js
import axios from 'axios'
import store from './store'
const http = axios.create()
let requestCount = 0
http.interceptors.request.use(config => {
requestCount++
store.commit('SHOW_LOADING', config.loadingText)
return config
})
http.interceptors.response.use(
response => {
requestCount--
if (requestCount === 0) {
store.commit('HIDE_LOADING')
}
return response
},
error => {
requestCount--
if (requestCount === 0) {
store.commit('HIDE_LOADING')
}
return Promise.reject(error)
}
)
export default http
使用CSS样式优化Loading效果
为Loading组件添加样式增强视觉效果。
.global-loading {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
z-index: 9999;
}
.loading-spinner {
width: 50px;
height: 50px;
border: 5px solid #f3f3f3;
border-top: 5px solid #3498db;
border-radius: 50%;
animation: spin 1s linear infinite;
}
.loading-text {
margin-top: 20px;
color: white;
font-size: 16px;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
使用第三方库实现高级Loading效果
对于更复杂的需求,可以考虑使用第三方库如element-ui或vant的Loading组件。
// 使用element-ui的Loading
import { Loading } from 'element-ui'
let loadingInstance
Vue.prototype.$loading = {
show() {
loadingInstance = Loading.service({
lock: true,
text: '加载中',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.7)'
})
},
hide() {
loadingInstance.close()
}
}






