vue实现loading插件
Vue 实现 Loading 插件的方法
创建基础组件
在 components 目录下创建 Loading.vue 文件,定义加载动画和样式。例如:
<template>
<div class="loading-overlay" v-if="isVisible">
<div class="loading-spinner"></div>
<p class="loading-text">{{ text }}</p>
</div>
</template>
<script>
export default {
props: {
isVisible: Boolean,
text: {
type: String,
default: 'Loading...'
}
}
};
</script>
<style>
.loading-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
display: flex;
flex-direction: column;
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>
封装插件逻辑
在 plugins 目录下创建 loading.js,通过 Vue 的插件机制扩展全局功能:

import Vue from 'vue';
import LoadingComponent from '@/components/Loading.vue';
const LoadingPlugin = {
install(Vue) {
const LoadingConstructor = Vue.extend(LoadingComponent);
let loadingInstance = null;
Vue.prototype.$loading = {
show(text = 'Loading...') {
if (!loadingInstance) {
loadingInstance = new LoadingConstructor({
propsData: { isVisible: true, text }
}).$mount();
document.body.appendChild(loadingInstance.$el);
}
},
hide() {
if (loadingInstance) {
document.body.removeChild(loadingInstance.$el);
loadingInstance.$destroy();
loadingInstance = null;
}
}
};
}
};
Vue.use(LoadingPlugin);
全局注册插件
在 main.js 中引入并注册插件:
import LoadingPlugin from '@/plugins/loading';
Vue.use(LoadingPlugin);
使用插件
在组件或请求拦截器中调用:

// 显示加载
this.$loading.show('数据加载中...');
// 隐藏加载
this.$loading.hide();
结合 Axios 拦截器
在请求拦截器中自动显示/隐藏 Loading:
import axios from 'axios';
let loadingCount = 0;
axios.interceptors.request.use(config => {
if (loadingCount === 0) {
Vue.prototype.$loading.show();
}
loadingCount++;
return config;
});
axios.interceptors.response.use(
response => {
loadingCount--;
if (loadingCount === 0) {
Vue.prototype.$loading.hide();
}
return response;
},
error => {
loadingCount--;
if (loadingCount === 0) {
Vue.prototype.$loading.hide();
}
return Promise.reject(error);
}
);
可选配置扩展
支持自定义颜色、大小等配置:
Vue.prototype.$loading = {
show(options = {}) {
const defaults = { text: 'Loading...', color: '#3498db', size: 40 };
const config = { ...defaults, ...options };
// 应用配置到组件实例
}
};
通过以上方法可以实现一个功能完善的 Vue Loading 插件,支持全局调用和自定义配置。






