vue 实现loading
Vue 实现 Loading 效果的方法
使用第三方库(如 Element UI、Ant Design Vue)
安装对应的 UI 库(以 Element UI 为例):
npm install element-ui
在 Vue 项目中引入并使用 Loading 组件:
import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);
// 在组件中调用 Loading
this.$loading({
lock: true,
text: '加载中',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.7)'
});
// 关闭 Loading
const loadingInstance = this.$loading();
loadingInstance.close();
自定义全局 Loading 组件
创建一个全局 Loading 组件(如 Loading.vue):
<template>
<div v-if="visible" class="loading-overlay">
<div class="loading-spinner"></div>
<p class="loading-text">{{ text }}</p>
</div>
</template>
<script>
export default {
props: {
visible: Boolean,
text: {
type: String,
default: '加载中...'
}
}
};
</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>
在 main.js 中注册为全局组件:
import Vue from 'vue';
import Loading from './components/Loading.vue';
Vue.component('Loading', Loading);
在需要的地方使用:
<template>
<div>
<Loading :visible="isLoading" text="数据加载中..." />
</div>
</template>
<script>
export default {
data() {
return {
isLoading: false
};
},
methods: {
fetchData() {
this.isLoading = true;
// 模拟异步请求
setTimeout(() => {
this.isLoading = false;
}, 2000);
}
}
};
</script>
使用 Vuex 管理全局 Loading 状态
在 Vuex 中定义状态:
// store.js
export default new Vuex.Store({
state: {
isLoading: false
},
mutations: {
setLoading(state, isLoading) {
state.isLoading = isLoading;
}
}
});
在根组件中使用:
<template>
<div id="app">
<Loading :visible="$store.state.isLoading" />
<router-view />
</div>
</template>
在需要的地方调用:
this.$store.commit('setLoading', true);
// 异步操作完成后
this.$store.commit('setLoading', false);
使用路由守卫实现页面切换 Loading
在路由配置中添加全局守卫:

// router.js
router.beforeEach((to, from, next) => {
store.commit('setLoading', true);
next();
});
router.afterEach(() => {
setTimeout(() => {
store.commit('setLoading', false);
}, 500);
});






