v-for 数字排序 数组排序 加:key

< template >
< div >
{{ msg}}
< ul >
<li v-for="num in sortarr1" :key="num">{{num}}</li>
<li v-for="student in sortarr2" :key="student.age">{{student.name}}-{{student.age}}</li>
</ ul >
< router-view ></ router-view >
< div >{{ sortnum}} </ div >
</ div >
</ template >

< script >
export default {
name: 'hi',
data () {
return {
msg: '你好,这是hi页面',
arr1:[ 43, 23, 7, 98],
arr2:[{ 'name' : 'aa', 'age' : 2},{ 'name' : 'bb', 'age' : 12},{ 'name' : 'dd', 'age' : 42},{ 'name' : 'cc', 'age' : 30}]
}
},
computed:{
sortarr1:function(){
return this.arr1.sort(this.sortnum);
},
sortarr2:function(){
return this.sortByKey(this.arr2,'age')
}
},
methods:{
sortnum:function(a,b) {
return a-b;
},

sortByKey:function (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 >

< style scoped >

</ style >

猜你喜欢

转载自blog.csdn.net/taimaigai/article/details/80269652