vue中数组和对象的排序
1数组排序
2对象排序
一、前言
我在vue项目中遇到了一个表格排序的需求,根据某一项的值的大小从大到小调整数组顺序。
二、代码
股票
404_9@
404_9@
<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;
}
}
}
} @H_404_9@
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;
}
}
}
} @H_404_9@
1. 排序方法
这里用到的是数组的sort方法,这个方法有一个需要注意的地方,就是不传参数的话,将按字母顺序对数组中的元素进行排序,说得更精确点,是按照字符编码的顺序进行排序。这并不是我们想要的排序方法,所以必须要传参。
sort方法的参数是一个函数,这个函数提供了一个比较方法,要比较两个值,然后返回一个用于说明这两个值的相对顺序的数字。
- 若 a 小于 b,在排序后的数组中 a 应该出现在 b 之前,则返回一个小于 0 的值。
- 若 a 等于 b,则返回 0。
- 若 a 大于 b,则返回一个大于 0 的值。