如何使用 v-for 从数组中随机选取特定数量的项目?

How to randomly pick up specific number of items from an array using v-for?

我想根据用户输入从数组中随机 select 特定数量的项目。数组如下:

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

我有一种方法可以在用户单击 'generate' 按钮时随机排列数组。但是,我不知道如何使用 v-for 来控制项目的数量。如果我这样做

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

我会得到整个数组。

您可以利用 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">

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