Search code examples
javascriptvue.jsvuejs2v-for

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


I want to randomly select the specific number of items from an array based on the user input. The array is like:

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

I have a method for shuffling the array when the user clicks the 'generate' button. However, I don't know how can I control the number of items using v-for. If I do

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

I will just get the entire array.


Solution

  • You could take advantage by using Vue.js, so you could define a computed property called subArray as follow :

           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);
              }
           }
    

    in your template :

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

    Note: don't put your logic inside template it's not a good practice, so keep it in your script