Skip to content Skip to sidebar Skip to footer

Vue.js Proper Random Ordering Of V-for Loop

Have a list that i want to output in random order. I achieved this with computed property:
  • {{ li

Solution 1:

There are few minor errors with your code, One error is in your method: randomList, you are using this.rand where rand is passed as parameter, so you just need to access it via rand, with this.rand it will look into vue instance data and will give following error:

TypeError: this.rand is undefined[Learn More]

See working fiddle here

Code:

  methods: {
    randomList: function(rand){
      return rand.sort(function(){return0.5 - Math.random()});
    }
  }

You have one typo here: el:'#vapp', => this shoud be el:'#app',

Solution 2:

The list (array) needs to be randomized using javascript, it has nothing to do with Vue.js or v-for.

Your approach seems correct. I would also create a method to randomize the array items like randomList(myList) and use it directly in v-for.

But instead of using sort function with a random true/false return value, there is a better implementation to shuffle array: How to randomize (shuffle) a JavaScript array?

If you look at the third answer that uses sort() to randomize (similar to your attempt), you will know that it is an incorrect approach. (explained in comments)

The top most answer has the right approach, which you can plug into your randomList() method. Here is how you can do it (similar to the accepted answer in that question, but uses a new array, leaving the original list untouched):

methods: {
    randomList: function(array){
        var currentIndex = array.length;
        var temporaryValue;
        var randomIndex;
        var myRandomizedList;

        // Clone the original array into myRandomizedList (shallow copy of array)
        myRandomizedList = array.slice(0)

        // Randomize elements within the myRandomizedList - the shallow copy of original array// While there remain elements to shuffle...while (0 !== currentIndex) {

            // Pick a remaining element...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            // And swap it with the current element.
            temporaryValue = myRandomizedList[currentIndex];
            myRandomizedList[currentIndex] = myRandomizedList[randomIndex];
            myRandomizedList[randomIndex] = temporaryValue;
        }

        // Return the new array that has been randomizedreturn myRandomizedList;
    }
}

Please note: I have not tested the above. It is just a copy-paste from the most popular answer, enclosed within your Vue component as a method, after making necessary changes for randomizing the cloned array.

Post a Comment for "Vue.js Proper Random Ordering Of V-for Loop"