【问题标题】:How to randomly pick up specific number of items from an array using v-for?如何使用 v-for 从数组中随机选取特定数量的项目?
【发布时间】:2018-10-01 20:27:47
【问题描述】:

我想根据用户输入从数组中随机选择特定数量的项目。数组是这样的:

arr: [
   1.png, 2.png, 3.png, ..., 100.png
]

我有一种方法可以在用户单击“生成”按钮时对数组进行洗牌。但是,我不知道如何使用 v-for 控制项目的数量。如果我这样做了

<img v-for="n in arr" :key="n" :src="/static/images/${n}.png">,

我会得到整个数组。

【问题讨论】:

  • v-for="n in arr.slice(0, howMany)"
  • 我知道推荐外部库是禁忌,但是如果你的项目中有 Lodash,那么就像 _.sampleSize(arr, 5) 从数组 lodash.com/docs#sampleSize 中选择 5 个随机元素一样简单
  • 谢谢,非常有帮助。我应该回顾一下数组的一些常用功能

标签: javascript vue.js vuejs2 v-for


【解决方案1】:

您可以利用 Vue.js,因此您可以定义一个名为 subArraycomputed 属性,如下所示:

       data(){
       return{
        ... 
       userInputValue:this.arr.length //by default get all the array, this property 
        }                              // is bound to input, it can be changed 
       }
      computed:{
         ...
         subArray(){
             return this.arr.splice(0,this.userInputValue);
          }
       }

在您的模板中:

  <img v-for="n in subArray" :key="n" :src="/static/images/${n}.png">

注意不要将您的逻辑放在模板中,这不是一个好习惯,因此请将其保留在您的脚本中

【讨论】:

    猜你喜欢
    • 2020-10-30
    • 2014-04-28
    • 2020-06-26
    • 2021-01-25
    • 2021-12-22
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多