Generate random number v-for


#1

I have a simple v-for loop working fine but I need to generate a random number 1-10 inside each for instance.

Is there a simple way to simply generate the digits?

Thanks

Dave


#2

Without knowing the full context of what you need exactly, it’s easy to generate a random number:

Math.ceil(Math.random()*10)

Of course if you wanted each number to be unique you would have to store a list of what numbers have already been used already


#3

I have something similar

Math.floor(Math.random() * (10 - 1 + 1)) + 1

But if wrapped in {{ }} i get inter-polarization error. Just not sure where to put it to make it work.

Thanks


#4

I would put that line in a method and call out to that method in your template, I’m not sire if you have access to the Math object within the template itself


#5

I have this method:

randomNumber: function () {
      this.random = Math.floor(Math.random() * (10 - 1 + 1)) + 1
    }

But how to call it from inside the v-for loop?

Thanks,

Dave


#6
<template>
  <div v-for="x in thingy">
    {{randomNumber()}}
  </div>
</template>
<script>
export default {
  methods : {
    randomNumber : function(){
      return Math.floor(Math.random() * (10 - 1 + 1)) + 1;
    }
  }
}
</script>

#7

Sweet!

Thanks man works perfect !!!

Much appreciated

Dave


#8

Nice
thanks