vue实现占位加载效果
使用骨架屏(Skeleton Screen)
骨架屏是一种常见的占位加载效果,通过灰色块状区域模拟内容布局。
<template>
<div class="skeleton-container">
<div class="skeleton-item" v-for="i in 5" :key="i"></div>
</div>
</template>
<style>
.skeleton-container {
width: 100%;
}
.skeleton-item {
height: 20px;
background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
background-size: 200% 100%;
margin-bottom: 10px;
animation: shimmer 1.5s infinite;
}
@keyframes shimmer {
0% { background-position: 200% 0; }
100% { background-position: -200% 0; }
}
</style>
使用v-if和加载状态
结合v-if指令和加载状态变量控制占位与真实内容的切换。
<template>
<div>
<div v-if="loading" class="placeholder">
<!-- 占位内容 -->
</div>
<div v-else>
<!-- 真实内容 -->
</div>
</div>
</template>
<script>
export default {
data() {
return {
loading: true
}
},
mounted() {
setTimeout(() => {
this.loading = false
}, 2000)
}
}
</script>
内容渐显动画
通过CSS过渡效果实现内容加载后的平滑显示。
<template>
<div :class="{ 'fade-in': !loading }">
<!-- 内容区域 -->
</div>
</template>
<style>
.fade-in {
animation: fadeIn 0.5s ease-in;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
</style>
图片懒加载占位
为图片加载设置占位背景和加载动画。
<template>
<div class="image-placeholder">
<img
:src="imageUrl"
@load="handleLoad"
v-show="!loading"
>
</div>
</template>
<style>
.image-placeholder {
position: relative;
background: #f5f5f5;
overflow: hidden;
}
.image-placeholder::after {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: linear-gradient(90deg, #eee 8%, #ddd 18%, #eee 33%);
background-size: 800px 100%;
animation: shimmer 1.5s infinite linear;
}
</style>
列表加载占位
为列表数据加载设计专门的占位效果。
<template>
<ul>
<li v-for="item in items" :key="item.id">
<!-- 真实内容 -->
</li>
<li v-if="loading" class="list-placeholder" v-for="n in 3" :key="'ph-'+n">
<div class="ph-row">
<div class="ph-avatar"></div>
<div class="ph-content">
<div class="ph-line"></div>
<div class="ph-line"></div>
</div>
</div>
</li>
</ul>
</template>
<style>
.list-placeholder {
padding: 12px;
}
.ph-row {
display: flex;
}
.ph-avatar {
width: 40px;
height: 40px;
border-radius: 50%;
background: #eee;
margin-right: 12px;
}
.ph-line {
height: 12px;
background: #eee;
margin-bottom: 8px;
border-radius: 4px;
}
.ph-line:last-child {
width: 80%;
}
</style>






