最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Vue.js proper random ordering of v-for loop - Stack Overflow

programmeradmin3浏览0评论

Have a list that i want to output in random order.

I achieved this with puted property:

<div id="app">

  <ul>
    <li v-for="list in randomList" >
      {{ list.text }}
    </li>
  </ul>

</div> 

<script>
      var vm = new Vue({


      el:'#app', 
      data:{
        lists:[
          {text:'js',value:'one'},
          {text:'css',value:'two'}, 
          {text:'html',value:'three'}
        ]
      },

      puted: {
        randomList: function(){
          return this.lists.sort(function(){return 0.5 - Math.random()});
        }
      }

    });
 </script>

But if i have more than one list i that want to simplify this process by applying methods or filters?

I tried with methods without success:

<div id="app">

  <ul>
    <li v-for="list in randomList(lists)" >
      {{ list.text }}
    </li>
  </ul>
   <ul>
     <li v-for="name in randomList(names)" >
     {{ name.text }}
    </li>
  </ul>


</div> 
<script>
      var vm = new Vue({


      el:'#app', 
      data:{
        lists:[
          {text:'js',value:'one'},
          {text:'css',value:'two'}, 
          {text:'html',value:'three'}
        ],
        names:[
          {text:'mary',value:'one'},
          {text:'css',value:'two'}, 
          {text:'html',value:'three'}
        ]
      },

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

    });
 </script>

Have a list that i want to output in random order.

I achieved this with puted property:

<div id="app">

  <ul>
    <li v-for="list in randomList" >
      {{ list.text }}
    </li>
  </ul>

</div> 

<script>
      var vm = new Vue({


      el:'#app', 
      data:{
        lists:[
          {text:'js',value:'one'},
          {text:'css',value:'two'}, 
          {text:'html',value:'three'}
        ]
      },

      puted: {
        randomList: function(){
          return this.lists.sort(function(){return 0.5 - Math.random()});
        }
      }

    });
 </script>

But if i have more than one list i that want to simplify this process by applying methods or filters?

I tried with methods without success:

<div id="app">

  <ul>
    <li v-for="list in randomList(lists)" >
      {{ list.text }}
    </li>
  </ul>
   <ul>
     <li v-for="name in randomList(names)" >
     {{ name.text }}
    </li>
  </ul>


</div> 
<script>
      var vm = new Vue({


      el:'#app', 
      data:{
        lists:[
          {text:'js',value:'one'},
          {text:'css',value:'two'}, 
          {text:'html',value:'three'}
        ],
        names:[
          {text:'mary',value:'one'},
          {text:'css',value:'two'}, 
          {text:'html',value:'three'}
        ]
      },

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

    });
 </script>
Share Improve this question edited Feb 4, 2017 at 22:07 Roslan Elyashiv asked Feb 4, 2017 at 11:55 Roslan ElyashivRoslan Elyashiv 1751 gold badge2 silver badges10 bronze badges 1
  • 1 You are getting any error with the method approach? – Saurabh Commented Feb 4, 2017 at 12:24
Add a ment  | 

2 Answers 2

Reset to default 4

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(){return 0.5 - Math.random()});
    }
  }

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

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 ments)

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 randomized
        return myRandomizedList;
    }
}

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

发布评论

评论列表(0)

  1. 暂无评论