Vue中如何给props传入指定长度的范围数组用于占位渲染?
你写法的问题出在两点:
new Array(16).keys()返回的是数组迭代器对象,不是可直接遍历的普通数组- 你额外在外层套了一层
[],才会得到嵌套数组结构
最简实现方案
如果不关心占位项的具体值,只需要长度为16的数组,直接用扩展运算符展开迭代器即可:
:items="[...new Array(16).keys()]"
得到的结果是[0,1,2,...,15],完全满足骨架屏占位的需求。
如果需要占位项的值为1到16的序列,可以加一层map处理:
:items="[...new Array(16).keys()].map(i => i + 1)"
兼容性更好的写法(适配低版本JS环境/Vue2项目)
用Array.from生成目标数组,语法更直观:
:items="Array.from({length: 16}, (_, index) => index + 1)"
优化后的完整代码
<VideoGrid v-if="isFetching && !videoList" :items="[...new Array(16).keys()]"> <template> <ItemPlaceholder /> </template> </VideoGrid> <VideoGrid v-else :items="videoList"> <template v-slot="slotProps"> <VideoComponent :title="slotProps.title" /> </template> </VideoGrid>
内容的提问来源于stack exchange,提问作者moCarl83
相关产品推荐
相关产品推荐

