v-skeleton 指令
介绍
v-skeleton 指令用于在异步数据加载时,显示骨架屏以提升用户体验。
基础用法
在需要显示骨架屏的元素上使用 v-skeleton 指令:
查看代码
vue
<template>
<div v-skeleton="skeletonProps" style="height: 100px; width: 300px; border-radius: 8px;">
<div v-if="!isLoading" style="padding: 20px; font-size: 16px; color: var(--vp-c-text); border: 1px solid #ccc;">
异步获取数据成功
</div>
</div>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { vSkeleton } from '@cp-vuedir/core';
const isLoading = ref(true);
const skeletonProps = ref({
isLoading: isLoading.value,
blocks: [
{ width: '100%', height: 20, top: 10 },
{ width: '80%', height: 16, top: 40 }
],
animation: 'wave',
bgColor: '#f8f9fa',
highlightColor: '#e9ecef'
})
onMounted(() => {
setTimeout(() => {
isLoading.value = false;
skeletonProps.value = { ...skeletonProps.value, isLoading: isLoading.value }
}, 2000);
})
</script>
<style>
@keyframes wave {
0% {
background-position: 200% 0;
}
100% {
background-position: -200% 0;
}
}
.skeleton-animation-wave {
background: linear-gradient(90deg,
var(--bg, rgb(64, 35, 35)) 25%,
var(--highlight, rgb(230, 139, 139)) 50%,
var(--bg, rgb(187, 135, 135)) 75%);
background-size: 200% 100%;
animation: wave 1.5s linear infinite;
}
.skeleton-block {
border-radius: 4px;
}
</style>
API
属性名 | 说明 | 类型 | 是否必选 | 默认值 |
---|---|---|---|---|
isLoading | 是否显示骨架屏 | boolean | - | |
blocks | 骨架屏的块配置,用于定义每个块的大小和位置 | BlockConfig[] | [] | |
animation | 骨架屏的动画效果,可选值为 "pulse" 或 "wave" 或 "none" | string | wave | |
bgColor | 骨架屏的背景颜色 | string | #f0f0f0 | |
highlightColor | 骨架屏的高亮颜色 | string | #c0c0c0 | |
width | 块的宽度 | string | number | - | |
height | 块的高度 | string | number | - | |
top | 块的顶部偏移量 | string | number | 0 | |
left | 块的左侧偏移量 | string | number | 0 |
注意事项
注意
- 目标元素的
position
属性:如果目标元素的position
为static
,指令会自动将其设置为relative
,以确保骨架屏的定位正确。如果目标元素已经设置了position
为relative
、absolute
或fixed
,则不会修改其position
属性。 - 当
isLoading
的值发生变化时,指令会自动更新骨架屏的显示状态。如果blocks
、animation
、bgColor
或highlightColor
发生变化,需要重新挂载指令