在我們工作中經常會遇到數組排序這樣的東西,遇到了順便就記錄下來
<div v-for="student,index in sortStudent" :key="index">
{{index+1}} {{ student.name }}--{{student.age}}
</div>
vue代碼
student: [{
name: 'Sugar',
age: '23'
},
{
name: 'Yang',
age: '20'
},
{
name: 'xiucheng',
age: '18'
}
]
}
js
computed:{
sortStudent:function(){
return sortByKey(this.student,'age')
}
}
//數組對象方法排序
function sortByKey(array,key){
return array.sort(function(a,b){
var x=a[key];
var y=b[key];
return ((x<y)?-1:(x>y)?1:0)
})
}
