我在vue项目中遇到了一个表格排序的需求,根据某一项的值的大小从大到小调整数组顺序。vue
表格大概是这个样子,样式和图片在代码中简化了。数组
<table class="recommend_table" cellspacing="0"> <tr> <th>股票</th> <th @click="sort('in_price')">入选价</th> <th @click="sort('now_price')">最新价</th> <th @click="sort('increase')">模拟涨跌幅</th> </tr> <tr v-for="(item,index) in recommendlist" :key="index"> <td> <div class="recommend_name">{{item.name}}</div> <div class="recommend_num">{{item.bn}}</div> </td> <td>{{item.in_price}}</td> <td>{{item.now_price}}</td> <td>{{item.increase}}%</td> </tr> </table> <script type="text/ecmascript-6"> export default { data(){ return{ recommendlist: [ { name:'高科石化', bn:'002778', in_price: 20.68, now_price: 28.68, increase: 10.01 }, { name:'中孚信息', bn:'300659', in_price: 19.46, now_price: 17.46, increase: 9.06 }, { name:'永福股份', bn:'300712', in_price: 17.68, now_price: 32.68, increase: 2.01 } ], sortType: 'in_price' } }, methods: { sort(type) { this.sortType = type; this.recommendlist.sort(this.compare(type)); // switch(type){ // case 'in_price': // this.sortType = 'in_price'; // this.recommendlist.sort(this.compare('in_price')); // break; // case 'now_price': // this.sortType = 'now_price'; // this.recommendlist.sort(this.compare('now_price')); // break; // case 'increase': // this.sortType = 'increase'; // this.recommendlist.sort(this.compare('increase')); // break; // } }, compare(attr) { return function(a,b){ var val1 = a[attr]; var val2 = b[attr]; return val2 - val1; } } } } </script>
这里用到的是数组的sort方法,这个方法有一个须要注意的地方,就是不传参数的话,将按字母顺序对数组中的元素进行排序,说得更精确点,是按照字符编码的顺序进行排序。这并非咱们想要的排序方法,因此必需要传参。ecmascript
sort方法的参数是一个函数,这个函数提供了一个比较方法,要比较两个值,而后返回一个用于说明这两个值的相对顺序的数字。函数
compare(key) { return function(a,b){ var val1 = a[key]; var val2 = b[key]; return val2 - val1; } }
在代码中,compare函数中的匿名函数就是这样一个函数,但这个函数外面又嵌套了一层,这是由于须要根据数组中的某一项来排序,因此须要把这一项的key值传进来。this
sort(type) { this.sortType = type; this.recommendlist.sort(this.compare(type)); // 注释部分 switch(type){ case 'in_price': this.sortType = 'in_price'; this.recommendlist.sort(this.compare('in_price')); break; case 'now_price': this.sortType = 'now_price'; this.recommendlist.sort(this.compare('now_price')); break; case 'increase': this.sortType = 'increase'; this.recommendlist.sort(this.compare('increase')); break; } }
一开始我按照注释的部分写的,和我同样抽象能力不是特别好的人首先会想到要这样写,可是写出来以后发现三种状况不过是重复的代码,这时我就直接用最上面两行代码来代替,写完之后感受心里一片平和。这种复用率高的代码简直让人太舒服了。编码
虽然是一个简单的功能,可是很是值得概括总结一下。spa