You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue中如何给props传入指定长度的范围数组用于占位渲染?

你写法的问题出在两点:

  1. new Array(16).keys()返回的是数组迭代器对象,不是可直接遍历的普通数组
  2. 你额外在外层套了一层[],才会得到嵌套数组结构

最简实现方案

如果不关心占位项的具体值,只需要长度为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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 14:57:02