过滤与排序
-
简述:使用计算属性来返回过滤或排序后的数组
-
例:
-
过滤(列出名字带有三字的学生姓名):
<div id="app"> <ul> <li v-for="student in filterStudents">{{student.name}}</li> </ul> </div> <script type="text/javascript" src="../js/vue.js"></script> <script type="text/javascript"> new Vue({ el:'#app', data:{ students:[ {name:'张三', id:1}, {name:'李三四', id:2}, {name:'王五', id:3} ] }, computed:{ filterStudents:function(){ return this.students.filter(function(item){ return item.name.match(/三/); }) } } }) </script>
-
排序(将学生姓名按长度从小到大排列展示)
<div id="app"> <ul> <li v-for="student in sortedStudents">{{student.name}}</li> </ul> </div> <script type="text/javascript" src="../js/vue.js"></script> <script type="text/javascript"> new Vue({ el:'#app', data:{ students:[ {name:'张三四', id:3}, {name:'李五', id:2}, {name:'王六七八', id:1} ] }, computed:{ sortedStudents:function(){ return this.students.sort(function(a, b){ return a.name.length - b.name.length; }) } } }) </script>
- 想要按名字长度从大到小排就将比较条件换为
b.name.length - a.name.length;
- 想要按名字长度从大到小排就将比较条件换为
-