【问题标题】:Vue: how to set props to an array range?Vue:如何将道具设置为数组范围?
【发布时间】:2021-10-16 07:35:44
【问题描述】:

我为视频创建了一个网格。它调用 api 以返回视频。我有一个状态 isFetching 在页面加载并尝试从 API 检索列表时设置为 true。取回视频后,isFetching设置为false,数据存储为videoList

如果 API 需要一段时间来获取,我会为每个项目使用带有占位符组件的网格。 VideoGrid 需要 items 因为在它内部,它会遍历它。我想要 16 个网格项目,但我不想做:items=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]。我试过:items="[new Array(16).keys()] 但这似乎创建了一个嵌套数组。有没有办法做到这一点而不必像那样写出来?

Main.vue

<VideoGrid v-if="isFetching && !videoList" :items="[1,2,3,4,5,6]">
  <template>
    <ItemPlaceholder />
  </template>
</VideoGrid>

<VideoGrid v-else :items="videoList">
  <template v-slot="slotProps>
    <VideoComponent :title="slotProps.title" />
  </template>
</VideoGrid>

【问题讨论】:

    标签: vue.js vuejs2 vue-component


    【解决方案1】:

    您应该能够像这样从 items 声明中删除括号:

    <VideoGrid v-if="isFetching && !videoList" :items="Array(16).fill(1)">
      <template>
        <ItemPlaceholder />
      </template>
    </VideoGrid>
    
    <VideoGrid v-else :items="videoList">
      <template v-slot="slotProps>
        <VideoComponent :title="slotProps.title" />
      </template>
    </VideoGrid>
    

    Array(16).fill(1) 将创建一个包含 16 个数字 1 的数组。如果你想在你的数组中有递增的值,你可以使用Array.from({length: 16}, (v, i) =&gt; i) 或查看How to initialize an array's length in JavaScript?

    【讨论】:

      猜你喜欢
      • 2018-05-07
      • 1970-01-01
      • 2022-12-01
      • 2017-05-24
      • 2021-08-30
      • 2013-09-01
      • 2017-07-04
      • 2019-05-08
      • 2019-04-08
      相关资源
      最近更新 更多