vue实现加载动画
Vue 实现加载动画的方法
使用 CSS 动画
通过 Vue 的 v-if 或 v-show 控制动画显示,结合 CSS 实现旋转或进度条效果:
<template>
<div class="loading" v-show="isLoading">
<div class="spinner"></div>
</div>
</template>
<style>
.loading {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.5);
display: flex;
justify-content: center;
align-items: center;
}
.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); }
}
</style>
使用第三方库(如 Vuetify)
Vuetify 提供预置的加载组件:
<template>
<v-progress-circular
indeterminate
color="primary"
v-if="loading"
></v-progress-circular>
</template>
<script>
import { VProgressCircular } from 'vuetify/lib'
export default {
components: { VProgressCircular },
data: () => ({ loading: true })
}
</script>
动态路由加载动画
在 Vue Router 的全局守卫中添加加载状态:
router.beforeEach((to, from, next) => {
store.commit('SET_LOADING', true)
next()
})
router.afterEach(() => {
setTimeout(() => store.commit('SET_LOADING', false), 500)
})
骨架屏技术
数据加载前显示占位图形:
<template>
<div v-if="loading" class="skeleton">
<div class="skeleton-line"></div>
<div class="skeleton-line"></div>
</div>
<div v-else>实际内容</div>
</template>
<style>
.skeleton-line {
height: 20px;
background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
background-size: 200% 100%;
animation: shimmer 1.5s infinite;
}
@keyframes shimmer {
to { background-position: -200% 0; }
}
</style>
按需加载动画
通过动态导入显示加载状态:

const AsyncComponent = () => ({
component: import('./Component.vue'),
loading: LoadingComponent,
error: ErrorComponent,
delay: 200,
timeout: 3000
})
注意事项
- 动画持续时间建议控制在 300-1000ms 之间
- 移动端需考虑性能影响,避免复杂动画
- 提供无障碍支持,添加 ARIA 属性
- 全局加载状态建议使用 Vuex 管理
- 网络请求可结合 axios 拦截器控制显示






