vue实现占位加载效果
Vue 实现占位加载效果的方法
使用骨架屏(Skeleton Screen)
骨架屏是一种常见的占位加载效果,通过模拟内容布局提升用户体验。Vue 中可以通过自定义组件实现。
<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%;
animation: shimmer 1.5s infinite;
margin-bottom: 10px;
border-radius: 4px;
}
@keyframes shimmer {
from { background-position: 200% 0; }
to { background-position: -200% 0; }
}
</style>
结合 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>
使用第三方库
Vue 生态中有专门的库可以快速实现骨架屏效果,例如 vue-skeleton-webpack-plugin 或 vue-content-loading。

安装 vue-content-loading:
npm install vue-content-loading
使用示例:

<template>
<content-loader>
<rect x="0" y="0" rx="3" ry="3" width="250" height="10" />
<rect x="0" y="20" rx="3" ry="3" width="150" height="10" />
</content-loader>
</template>
<script>
import { ContentLoader } from 'vue-content-loading'
export default {
components: {
ContentLoader
}
}
</script>
列表数据加载占位
对于列表数据,可以结合 v-for 实现多个占位项。
<template>
<ul>
<li v-for="n in placeholderCount" :key="n" class="list-placeholder">
<div class="avatar-placeholder"></div>
<div class="text-placeholder"></div>
</li>
</ul>
</template>
<style>
.list-placeholder {
display: flex;
align-items: center;
margin-bottom: 15px;
}
.avatar-placeholder {
width: 40px;
height: 40px;
border-radius: 50%;
background-color: #eee;
margin-right: 15px;
}
.text-placeholder {
width: 200px;
height: 16px;
background-color: #eee;
}
</style>
图片懒加载占位
图片加载时可以显示占位背景。
<template>
<div class="image-container">
<img
v-if="loaded"
:src="imageUrl"
@load="loaded = true"
>
<div v-else class="image-placeholder"></div>
</div>
</template>
<style>
.image-placeholder {
width: 100%;
height: 200px;
background: #f5f5f5;
}
</style>
以上方法可以根据实际需求组合使用,骨架屏动画和样式可以进一步自定义优化。






