vue中数组和对象的排序

2021-08-19  本文已影响0人  曲昶光

1数组排序

<div id="app">
     <ul>
          <li v-for="a in arr1">{{a}}</li>
     </ul>
 </div>
        <script type="text/javascript">
            new Vue({
                el:"#app",
                data:{
                    arr:[1,4,5,2,3,44]
                },computed:{
                    arr1:function(){
                        return this.arr.sort(sortNum)//调用排序方法
                    }
                }
            })
            function sortNum(a,b){//排序方法
                return a-b;
            }
        </script>

2对象排序

<div id="app">
              <ul>
                 <li v-for="(stu,index) in students1">{{stu}}</li>
              </ul>
          </div>
          <script type="text/javascript">
              new Vue({
                  el:"#app",
                  data:{
                     students:[
                         {name:"小a",age:20},
                         {name:"小b",age:21},
                         {name:"小c",age:18},
                         {name:"小d",age:19},
                        {name:"小f",age:18}
                     ]
                 },
                 computed:{
                     students1:function(){
                        return sortKey(this.students,'age')
                     }
                 }
             })
             function sortKey(array,key){
                 return array.sort(function(a,b){
                     var x = a[key];
                     var y = b[key];
                     return ((x<y)?-1:(x>y)?1:0)
                 })
            }
         </script>

转自(https://www.cnblogs.com/lisy001/p/9052050.html)

上一篇下一篇

猜你喜欢

热点阅读