美文网首页
vue中数组和对象的排序

vue中数组和对象的排序

作者: 曲昶光 | 来源:发表于2021-08-19 18:54 被阅读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)

    相关文章

      网友评论

          本文标题:vue中数组和对象的排序

          本文链接:https://www.haomeiwen.com/subject/qcpabltx.html