vue骨架屏实现
Vue 骨架屏实现方法
使用专用库(如vue-skeleton-webpack-plugin)
安装插件依赖:
npm install vue-skeleton-webpack-plugin --save-dev
创建骨架屏组件(Skeleton.vue):
<template>
<div class="skeleton">
<div class="skeleton-head"></div>
<div class="skeleton-body">
<div class="skeleton-title"></div>
<div class="skeleton-content"></div>
</div>
</div>
</template>
<style scoped>
.skeleton {
padding: 15px;
}
.skeleton-head {
height: 40px;
background: #f2f2f2;
}
.skeleton-title {
height: 20px;
margin-top: 10px;
background: #f2f2f2;
}
.skeleton-content {
height: 60px;
margin-top: 10px;
background: #f2f2f2;
}
</style>
配置webpack:
// vue.config.js
const SkeletonWebpackPlugin = require('vue-skeleton-webpack-plugin')
module.exports = {
configureWebpack: {
plugins: [
new SkeletonWebpackPlugin({
webpackConfig: {
entry: require.resolve('./src/skeleton.entry.js')
},
minimize: true,
quiet: true
})
]
}
}
纯CSS实现方案
通过v-if控制显示状态:
<template>
<div>
<div v-if="loading" class="skeleton">
<!-- 骨架屏结构 -->
</div>
<div v-else>
<!-- 实际内容 -->
</div>
</div>
</template>
<style>
.skeleton-item {
background: linear-gradient(90deg, #f2f2f2 25%, #e6e6e6 37%, #f2f2f2 63%);
background-size: 400% 100%;
animation: skeleton-loading 1.4s ease infinite;
}
@keyframes skeleton-loading {
0% { background-position: 100% 50% }
100% { background-position: 0 50% }
}
</style>
基于路由的动态骨架屏
创建路由对应骨架组件:
// router.js
const routes = [
{
path: '/product',
component: () => import('@/views/Product.vue'),
meta: {
skeleton: () => import('@/components/ProductSkeleton.vue')
}
}
]
路由守卫中处理:
router.beforeEach((to, from, next) => {
if (to.meta.skeleton) {
store.commit('SET_SKELETON', to.meta.skeleton())
}
next()
})
服务端渲染(SSR)方案
Nu.js中配置:
// nuxt.config.js
export default {
loading: {
color: '#3B8070',
height: '2px'
},
loadingIndicator: {
name: 'circle',
color: '#3B8070',
background: 'white'
}
}
自定义加载组件:
<!-- components/loading.vue -->
<template>
<div class="skeleton-wrapper">
<content-loader :width="400" :height="150">
<rect x="0" y="0" rx="3" ry="3" width="250" height="10" />
<rect x="20" y="20" rx="3" ry="3" width="220" height="10" />
<rect x="0" y="40" rx="3" ry="3" width="350" height="10" />
</content-loader>
</div>
</template>
关键实现要点:
- 保持骨架屏结构与真实DOM结构一致
- 使用CSS动画增强视觉效果
- 合理控制骨架屏显示时机
- 移动端需考虑响应式布局
- 可结合vuex管理加载状态
性能优化建议:

- 避免过多DOM节点
- 使用will-change优化动画
- 对重复骨架元素使用v-for
- 分块加载复杂页面区域






