vfor

  1. 一个简单排序,注意这里面sort方法容易掉的坑,不仅是vue所有的js都有这个bug,因此这种解决方式很常用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<title>Document</title>
</head>
<body>
<div id="app">
<ul>
<li v-for="item in sortItems">{{item}}</li>
//注意这里的sortItems别写成items了!
</ul>
</div>
<script>
new Vue({
el:"#app",
data:{
items:[1,4,3,78,45]
},
computed:{
sortItems://注意在vue中为了保护data这里必须重新命名不能用items
function(){
return this.items.sort(sortNum)
//若不再定义一个sortNum,将出现收字符排序完了再排下一个,如1,23,4,5,67
}

}
});
//注意这个函数写的位置,应写在vue后
function sortNum(a,b){
return a-b;
}
</script>

</body>
</html>

结果:
avatar

  1. 对象数组排序
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<title>Document</title>
</head>
<body>
<div id="app">
<ul>
<li v-for="(student,index) in sortStudents">{{index+1}}:{{student.name}}-{{student.age}}</li>
<!-- 注意这里的索引的用法 -->
</ul>
</div>
<script>
new Vue({
el:"#app",
data:{
students:
[
{name:'linguoqiang',age:21},
{name:'liuxue',age:21},
{name:'chenhong',age:20},
{name:'chenqianqian',age:19},
{name:'guomengyu',age:18},

]


},
computed:{
sortStudents:
//千万注意不要画蛇添足在这里加花括号,否则会出错
function(){
return sortByKey(this.students,'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));
});
}

</script>

</body>
</html>

结果:
avatar

-------------本文结束感谢您的阅读-------------