<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="app">
    <ul>
      <li v-for="student in sortStudent">
        {{ student }}
      </li>
    </ul>
  </div>
  <script src="node_modules/vue/dist/vue.js"></script>
  <script>
    new Vue({
      el: '#app',
      data() {
        return {
          students:[
            {name:'Lily',age:31},
            {name:'David',age:30},
            {name:'John',age:47},
            {name:'Mei',age:42}
          ]
        }
      },
      computed: {
        sortStudent: function () {
          return sortByKey(this.students, 'age');
        }
      }
    });
    function sortByKey(arr, key) {
      return arr.sort((a, b) => {
        // console.log(a);
        // console.log(b);
        var x = a[key];
        var y = b[key];
        // return x - y;
        // 若 x 小于 y,在排序后的数组中 x 应该出现在 y 之前,则返回一个小于 0 的值。
        // 若 x 等于 y,则返回 0。
        // 若 x 大于 y,则返回一个大于 0 的值。
        return ((x<y)?-1:((x>y)?1:0));
      });
    }
  </script>
</body>
</html>

 

 


版权声明:本文为u010234868原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/u010234868/article/details/120331110