vue实现加载动画
Vue 实现加载动画的方法
在 Vue 中实现加载动画可以通过多种方式完成,以下是一些常见的方法:
使用 CSS 动画
通过 CSS 定义动画效果,结合 Vue 的动态类绑定实现加载动画。以下是一个简单的旋转加载动画示例:
<template>
<div class="loading-container">
<div class="spinner" v-if="isLoading"></div>
</div>
</template>
<script>
export default {
data() {
return {
isLoading: true
}
}
}
</script>
<style>
.spinner {
width: 40px;
height: 40px;
border: 4px solid rgba(0, 0, 0, 0.1);
border-radius: 50%;
border-left-color: #09f;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
使用第三方库
Vue 生态中有许多优秀的加载动画库,如 vue-loading-spinner 或 vue-spinners,可以快速集成丰富的动画效果。
安装 vue-spinners:
npm install vue-spinners
使用示例:
<template>
<div>
<clip-loader :loading="isLoading" color="#36D7B7" size="50px"></clip-loader>
</div>
</template>
<script>
import { ClipLoader } from 'vue-spinners'
export default {
components: {
ClipLoader
},
data() {
return {
isLoading: true
}
}
}
</script>
自定义过渡动画
利用 Vue 的过渡系统 (<transition>) 实现加载动画,适合页面或组件切换时的加载效果。
<template>
<transition name="fade">
<div v-if="isLoading" class="loading-overlay">
<div class="loading-content">Loading...</div>
</div>
</transition>
</template>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
.loading-overlay {
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;
}
</style>
骨架屏加载动画
骨架屏是一种流行的加载方式,在内容加载前显示占位图形。
<template>
<div v-if="isLoading" 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;
margin-bottom: 10px;
}
@keyframes shimmer {
0% { background-position: 200% 0; }
100% { background-position: -200% 0; }
}
</style>
全局加载动画
通过 Vue 的全局状态管理(如 Vuex)或事件总线控制全局加载动画。
// 在 main.js 或单独的文件中
Vue.prototype.$showLoading = function() {
// 显示加载动画的逻辑
}
Vue.prototype.$hideLoading = function() {
// 隐藏加载动画的逻辑
}
在组件中使用:
this.$showLoading()
// 执行异步操作
this.$hideLoading()
以上方法可以根据项目需求灵活选择或组合使用。CSS 动画适合简单场景,第三方库提供丰富预设,骨架屏优化用户体验,全局加载适合复杂应用。







