vue实现全局加载动画
使用Vue插件封装全局加载动画
在Vue项目中创建一个自定义插件,通过Vue的插件系统实现全局调用。
创建src/plugins/loading.js文件:
const Loading = {
install(Vue) {
Vue.prototype.$loading = {
show() {
const loadingEl = document.createElement('div')
loadingEl.id = 'global-loading'
loadingEl.innerHTML = `
<div class="loading-overlay">
<div class="loading-spinner"></div>
</div>
`
document.body.appendChild(loadingEl)
},
hide() {
const loadingEl = document.getElementById('global-loading')
if (loadingEl) {
document.body.removeChild(loadingEl)
}
}
}
}
}
export default Loading
添加加载动画样式
在项目的全局CSS文件(如src/assets/styles/global.css)中添加样式:
.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 {
width: 50px;
height: 50px;
border: 5px solid #f3f3f3;
border-top: 5px solid #3498db;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
注册插件并全局使用
在main.js中注册插件:

import Vue from 'vue'
import Loading from './plugins/loading'
Vue.use(Loading)
在组件中使用:
// 显示加载动画
this.$loading.show()
// 隐藏加载动画
this.$loading.hide()
使用axios拦截器实现自动加载动画
可以与axios拦截器结合,实现请求时自动显示加载动画:

import axios from 'axios'
// 请求拦截器
axios.interceptors.request.use(config => {
Vue.prototype.$loading.show()
return config
}, error => {
Vue.prototype.$loading.hide()
return Promise.reject(error)
})
// 响应拦截器
axios.interceptors.response.use(response => {
Vue.prototype.$loading.hide()
return response
}, error => {
Vue.prototype.$loading.hide()
return Promise.reject(error)
})
使用Vuex管理加载状态
对于更复杂的应用,可以使用Vuex集中管理加载状态:
创建store模块:
const loadingModule = {
state: () => ({
isLoading: false
}),
mutations: {
SET_LOADING(state, status) {
state.isLoading = status
}
},
actions: {
showLoading({ commit }) {
commit('SET_LOADING', true)
},
hideLoading({ commit }) {
commit('SET_LOADING', false)
}
}
}
在根组件中使用v-if控制加载动画显示:
<template>
<div>
<div v-if="$store.state.loading.isLoading" class="global-loading">
<!-- 加载动画内容 -->
</div>
<router-view />
</div>
</template>





